 GeeksforGeeks App
Open App Browser
Continue

# C Program for Counting Sort

Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence.

Algorithm:

Step 1: Start
Step 2 : Find Largest Data From Array.
Step 3 : Set All Array Element Value with 0.
Step 4 : Increase Count Data Of Each Number Which Found In The Array .
Step 5 : Find Cumulative Frequency
Step 6: Store The Number In The Output Array.
Step 7 : Print The Output Array
Step 8 : Stop.

Pseudocode :

```COUNTINGSORT(A)
FOR I = 0 TO K DO
C[I] = 0
FOR J = 0 TO N DO
C[A[J]] = C[A[J]] + 1
FOR I = 1 TO K DO
C[I] = C[I] + C[I-1]
FOR J = N-1 TO 0 DO
B[ C[A[J]]-1 ] = A[J]
C[A[J]] = C[A[J]] - 1
END FUNCTION```

## C

 `// C Program for counting sort``#include ``#include ``#define RANGE 255` `// The main function that sort the given string arr[] in``// alphabetical order``void` `countSort(``char` `arr[])``{``    ``// The output character array that will have sorted arr``    ``char` `output[``strlen``(arr)];` `    ``// Create a count array to store count of individual``    ``// characters and initialize count array as 0``    ``int` `count[RANGE + 1], i;``    ``memset``(count, 0, ``sizeof``(count));` `    ``// Store count of each character``    ``for``(i = 0; arr[i]; ++i)``        ``++count[arr[i]];` `    ``// Change count[i] so that count[i] now contains actual``    ``// position of this character in output array``    ``for` `(i = 1; i <= RANGE; ++i)``        ``count[i] += count[i-1];` `    ``// Build the output character array``    ``for` `(i = 0; arr[i]; ++i)``    ``{``        ``output[count[arr[i]]-1] = arr[i];``        ``--count[arr[i]];``    ``}` `    ``// Copy the output array to arr, so that arr now``    ``// contains sorted characters``    ``for` `(i = 0; arr[i]; ++i)``        ``arr[i] = output[i];``}` `// Driver program to test above function``int` `main()``{``    ``char` `arr[] = ``"geeksforgeeks"``;``//"applepp";` `    ``countSort(arr);` `    ``printf``(``"Sorted character array is %sn"``, arr);``    ``return` `0;``}`

Output:

`Sorted character array is eeeefggkkorssn`

Time Complexity Analysis
Worst Case
When Data Is Skewed And Range Is Large Then Time Complexity Is O(N+K)
Best Case
When All Elements Are Same Time Complexity Is O(N+K)
Average Case
Average Time Complexity Is O(N+K)

Space Complexity :

SPACE COMPLEXITY FOR THIS SORT IS O(K).

1. Count  Sort Process Fast in less time .
2.  It Is A useful for Small size of  Data Set .