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

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 |

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

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).

ReplyDeleteAlso, 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.

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

ReplyDeleteWhy would you ever do this? Everyone knows that the fastest sort is the sleep sort.

ReplyDelete