## Hottest:

5 Ways to Earn First \$1000 From Your Blog

## counting sort algorithm in java

### Structure of the Problem Requirements

In this problem we will learn how to implement a 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 range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Here is the source code of this problem which help you in better understanding.

## 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 Program

 Counting Sort in Java