Counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, 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. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items.

Here is the source code of the C program to sort integers using Counting Sort technique. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

`#include <stdio.h>`

void countingsort(int arr[], 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[arr[j]] = C[arr[j]] + 1;

for (i = 1; i <= k; i++)

C[i] = C[i] + C[i-1];

for (j = n; j >= 1; j--)

`{`

B[C[arr[j]]] = arr[j];

C[arr[j]] = C[arr[j]] - 1;

`}`

printf("\nThe Sorted array is :\n");

for(i = 1; i <= n; i++)

printf(" %d", B[i]);

`}`

int main()

`{`

int n,i,k = 0, arr[15];

printf("Enter the number of elements : ");

scanf("%d", &n);

printf("\n\nEnter the elements to be sorted :\n");

for ( i = 1; i <= n; i++)

`{`

scanf("%d", &arr[i]);

if (arr[i] > k)

`{`

k = arr[i];

`}`

`}`

countingsort(arr, k, n);

return 0;

`}`

$ gcc countsort.c -o countsort $ ./countsort Enter the number of elements : 10 Enter the elements to be sorted : 8 11 34 2 1 5 4 9 6 47 The Sorted array is : 1 2 4 5 6 8 9 11 34 47

**Sanfoundry Global Education & Learning Series – 1000 C Programs.**

Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms.