Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

C Program for Counting Sort

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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. 


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 :

   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


// C Program for counting sort
#include <stdio.h>
#include <string.h>
#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)
    // 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];
    // 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";
    printf("Sorted character array is %sn", arr);
    return 0;


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 : 


Advantages :

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


  1. It Is Not useful Large Data.
  2. It Is Not useful for sorting string values .
  3. Not An In-Place Sorting Algorithm
  4.  It Requires Extra Additional Space for sorting operation. like  O(K)

Please refer complete article on Counting Sort for more details!

My Personal Notes arrow_drop_up
Last Updated : 08 Jun, 2022
Like Article
Save Article
Similar Reads
Related Tutorials