Blog Archives

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