## C Program To Sort Array using Counting Sort Algorithm

Learn how to Sort Array using Counting Sort Algorithm in C Programming Language. The counting sort in C works on a kind of Hashing function concept.

#### What is Counting Sort Algorithm?

The counting sort technique is based on keys between a specific range. This algorithm counts the number of objects having distinct key values after which a kind **hashing algorithm** is implemented to calculate the position of each object in the output series.

#### C Program To Sort Array using Counting Sort Algorithm

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #include <stdio.h> void counting_sort_function(int elements[], int temp, int limit); int main() { int limit, temp = 0, elements[50], count; printf("\nEnter Total Number of Elements To Sort:\t"); scanf("%d", &limit); printf("\nEnter The Elements To Sort:\t"); for(count = 1; count <= limit; count++) { scanf("%d", &elements[count]); if(elements[count] > temp) { temp = elements[count]; } } counting_sort_function(elements, temp, limit); printf("\n"); return 0; } void counting_sort_function(int elements[], int temp, int limit) { int count, j; int sorted_elements[50], x[50]; for(count = 0; count <= temp; count++) { x[count] = 0; } for(j = 1; j <= limit; j++) { x[elements[j]] = x[elements[j]] + 1; } for(count = 1; count <= temp; count++) { x[count] = x[count] + x[count - 1]; } for(j = limit; j >= 1; j--) { sorted_elements[x[elements[j]]] = elements[j]; x[elements[j]] = x[elements[j]] - 1; } printf("\nSorted List\n"); for(count = 1; count <= limit; count++) { printf("%d ", sorted_elements[count]); } } |

#### Output

If you have any compilation errors or doubts about Counting Sort in C Programming, let us know about it in the comment section below.

The Counting Sort Algorithm seems to be very interesting. A combination of Hash Tables and Sorting technique. It is amazing. Thanks for this C program.

Even though they run in O(n) time, they do not have much practical applications.

This code for algorithm on counting sort in C programming is really something new for me. Thanks for bringing this here.