Saturday, 15 December 2012

Write a Java Program to implement Counting Sort.

Counting Sort assumes that each of the n input elements is an integer range from 0 to k for some integer k. When k is in order of uper bound n then sort runs in order of n.

package counting.sort;
public class CountingSort
{
    public static void main(String[ ] args)
    {
         int [ ]A = {-1, 19,20,23,48,19,34,34,19,0,2};
         int [ ]C = new int[50];
       
         //Frequency of each element
         for(int i = 1;i<A.length;i++)
         {
             C[A[i]] = C[A[i]]+1;
         }
         //Cumulative Frequency
         for(int i = 1;i<C.length;i++)
         {
             C[i] = C[i]+C[i-1];
         }
       
         int [ ]B= new int[A.length];
         for(int i = A.length -1 ;i>=1;i--)
         {
             B[C[A[i]]] = A[i];
             C[A[i]] = C[A[i]] - 1;
         }
         print(B);  //B is sorted array
    }
    static void print(int [ ]A)
    {
        System.out.println();
        for(int i=0;i<A.length;i++)
        {
            if(i!=A.length-1)
                System.out.print(A[i]+ ",");
            else
                System.out.print(A[i]);;
        }
    }
   
}

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top