C program for Counting Sort Algorithm

C program for Counting Sort Algorithm

1607
3
SHARE

C program for Counting Sort AlgorithmCounting sort is an algorithm for sorting a collection of objects according to keys that are small integers i.e. it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence.

In the most general case, the input to counting sort consists of a collection of n items, each of which has a non-negative integer key whose maximum value is at most k.

Lets see how to write a .

C program for Counting Sort Algorithm :

#include<stdio.h>
#include<conio.h>
int Counting_sort(int A[], int k, int n)
{
	int i, j;
	int B[15], C[100];
	for(i = 0; i <= k; i++)
			C[i] = 0;
	for(j =1; j <= n; j++)
			C[A[j]] = C[A[j]] + 1;
	for(i = 1; i <= k; i++)
			C[i] = C[i] + C[i-1];
	for(j = n; j >= 1; j--)
	{
			B[C[A[j]]] = A[j];
			C[A[j]] = C[A[j]] - 1;
	}
	printf("\nThe Sorted array is :\n");
	for(i = 1; i <= n; i++)
	      printf("\t%d",B[i]);
}

int main()
{
	int n,i,k = 0, A[15];
    printf("-----------------------------------------------------------\n");
    printf("----------------------Made by C code champ-----------------\n");
    printf("-----------------------------------------------------------\n\n");
    printf("\t\tCOUNTING SORT ALGORITHM\n\n\n\n");
	printf("Enter the number of input : ");
	scanf("%d",&n);
	printf("\n\nEnter the elements to be sorted :\n");
	for ( i = 1; i <= n; i++)
	{
		 scanf("%d",&A[i]);
		 if(A[i] > k)
		 {
			k = A[i];
		 }
	}
	Counting_sort(A, k, n);
	getch();
}

 

We hope you all have enjoyed the for Counting Sort algorithm. If you have any doubts regarding the code, ask us in form of comments.

3 COMMENTS

LEAVE A REPLY