Counting Sort Algorithm in Java

Counting sort is an algorithm for sorting a collection of objects according to keys that are small integers. In counting sorting technique based on keys between a specific ranges. It works by counting the number of objects having distinct key values (kind of hashing). 

Source Code 


public class CountingSort {
      void count_sort(int a[],int b[],int k){
          int[] c=new int[k];
         for(int j=0;j<a.length;j++){
             c[a[j]]=c[a[j]]+1;
         }
         for(int i=1;i<k;i++){
             c[i]=c[i]+c[i-1];
         }
         for(int j=(a.length-1);j>=0;j--){
             b[c[a[j]]-1]=a[j];
             c[a[j]]=c[a[j]]-1;
         }
      }
      public static void main(String args[]){
          CountingSort ct=new CountingSort();
          int []a={1,4,3,1,2,3,0,3};
          int []b=new int[8];
          int k=10;
          try{
          ct.count_sort(a,b,k);
          }
catch(Exception e){};
          System.out.println("Sorted Array is:");
          for(int i=0;i<b.length;i++){
              System.out.print("["+b[i]+"]"+",");
          }
      }
}

                                          Output of the Program

Counting Sort in Java
Counting Sort in Java
Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

3 comments:

  1. What part? Counting sort is actually a well respected sorting algorithm in some (very specific) circumstances, being that it's got Theta(N) running time, which is much better than most sorting algorithms, which are n lg(n).
    Also, the source code they posted is particularly good because they didn't waste time on whitespace, or multiple character variable names. This is a smart tactic because the shorter the source file, the quicker the compiler can read it, speeding compilation.

    ReplyDelete
  2. It works great. No matter that happens, I don't get any errors.

    ReplyDelete
  3. Why would you ever do this? Everyone knows that the fastest sort is the sleep sort.

    ReplyDelete