Counting Sort

The Code Vault

Java Code To Illustrate Counting Sort:

 

package countingsort;

import java.util.Scanner;

public class CountingSort
{

public static void display(int A[])
{
for (int i=0;i<A.length;i++) System.out.print(A[i] + ” “);
System.out.println();
}

public static void CountingSort(int A[], int n, int k)
{
int i;
int B[] = new int[n];
int C[] = new int[k+1];
for (i=0;i<k+1;i++) C[i] = 0;
display(C);
for (i=0;i<n;i++) C[A[i]]++;
display(C);
for (i=1;i<k+1;i++) C[i] += C[i-1];
display(C);
for (i=A.length-1;i>=0;i–)
{
B[C[A[i]]-1] = A[i];
C[A[i]]–;
}
System.out.println(“Sorted Array:”);
display(B);
}

public static void main(String[] args)
{
Scanner x = new Scanner(System.in);
System.out.println(“Counting Sort”);
System.out.println(“Enter Number Of Elements”);
int n = x.nextInt();
int A[] = new int[n];
int max;
System.out.println(“Enter array”);
for (int i=0;i<n;i++) A[i] = x.nextInt();
max = A[0];
for (int i=0;i<n;i++) if (A[i]>max) max = A[i];
CountingSort(A,n,max);
}
}

View original post

Advertisements

About Khuram Ali

Programming... Programming and Programming...!!!

Posted on June 27, 2013, in Algorithms, Java and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: