Skip to content
Related Articles

Related Articles

C Program for Counting Sort
  • Last Updated : 04 Dec, 2018

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.

// C Program for counting sort
#include <stdio.h>
#include <string.h>
#define RANGE 255
// The main function that sort the given string arr[] in
// alphabatical 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 inidividul
    // 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

Please refer complete article on Counting Sort for more details!

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.

My Personal Notes arrow_drop_up
Recommended Articles
Page :