The Wayback Machine - https://web.archive.org/web/20230809231833/https://www.geeksforgeeks.org/counting-sort/
Skip to content
Related Articles
Open In App
Related Articles

Counting Sort – Data Structures and Algorithms Tutorials

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 (a kind of hashing). Then do some arithmetic operations to calculate the position of each object in the output sequence. 

How does Counting Sort Algorithm work?

  • For simplicity, consider the data in the range of 0 to 9. 
  • Input data: {1, 4, 1, 2, 7, 5, 2}
  • Take a count array to store the count of each unique object.

scene00721

  • Now, store the count of each unique element in the count array
  • If any element repeats itself, simply increase its count.

scene00865

  • Here, the count of each unique element in the count array is as shown below:
    • Index:  0  1  2  3  4  5  6  7  8  9
    • Count: 0  2  2  0   1  1  0  1  0  0

scene01153

  • Modify the count array such that each element at each index stores the sum of previous counts.
    • Index:   0  1  2  3  4  5  6  7  8  9
    • Count:  0  2  4  4  5  6  6  7  7  7
  • The modified count array indicates the position of each object in the output sequence.
  • Find the index of each element of the original array in the count array. This gives the cumulative count.

scene01297

scene01369

  • Rotate the array clockwise for one time.
    • Index:  0 1 2 3 4 5 6 7 8 9 
    • Count: 0 0 2 4 4 5 6 6 7 7

  scene02881

  •   Output each object from the input sequence followed by increasing its count by 1.
  •   Process the input data: {1, 4, 1, 2, 7, 5, 2}. The position of 1 is 0.
  •   Put data 1 at index 0 in output. Increase count by 1 to place next data 1 at an index 1 greater than this index.

scene02521

  • After placing each element in its correct position, decrease its count by one.
Recommended Problem

Below is the implementation of the above algorithm:

C++

// C++ Program for counting sort
#include <bits/stdc++.h>
#include <string.h>
using namespace std;
#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]];
    }

    /*
    For Stable algorithm
    for (i = sizeof(arr)-1; i>=0; --i)
    {
        output[count[arr[i]]-1] = arr[i];
        --count[arr[i]];
    }

    For Logic : See implementation
    */

    // Copy the output array to arr,
    // so that arr now contains
    // sorted characters
    for (i = 0; arr[i]; ++i)
        arr[i] = output[i];
}

// Driver code
int main()
{
    char arr[] = "geeksforgeeks";

    // Function call
    countSort(arr);

    cout << "Sorted character array is " << arr;
    return 0;
}

// This code is contributed by rathbhupendra

C

// 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)
        ++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]];
    }

    /*
     For Stable algorithm
     for (i = sizeof(arr)-1; i>=0; --i)
    {
        output[count[arr[i]]-1] = arr[i];
        --count[arr[i]];
    }

    For Logic : See implementation
    */

    // Copy the output array to arr, so that arr now
    // contains sorted characters
    for (i = 0; arr[i]; ++i)
        arr[i] = output[i];
}

// Driver code
int main()
{
    char arr[] = "geeksforgeeks"; //"applepp";

    // Function call
    countSort(arr);

    printf("Sorted character array is %s", arr);
    return 0;
}

Java

// Java implementation of Counting Sort

import java.io.*;

class CountingSort {
    void sort(char arr[])
    {
        int n = arr.length;

        // The output character array that will have sorted
        // arr
        char output[] = new char[n];

        // Create a count array to store count of individual
        // characters and initialize count array as 0
        int count[] = new int[256];
        for (int i = 0; i < 256; ++i)
            count[i] = 0;

        // store count of each character
        for (int i = 0; i < n; ++i)
            ++count[arr[i]];

        // Change count[i] so that count[i] now contains
        // actual position of this character in output array
        for (int i = 1; i <= 255; ++i)
            count[i] += count[i - 1];

        // Build the output character array
        // To make it stable we are operating in reverse
        // order.
        for (int i = n - 1; i >= 0; 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 (int i = 0; i < n; ++i)
            arr[i] = output[i];
    }

    // Driver code
    public static void main(String args[])
    {
        CountingSort ob = new CountingSort();
        char arr[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
                       'r', 'g', 'e', 'e', 'k', 's' };

        // Function call
        ob.sort(arr);

        System.out.print("Sorted character array is ");
        for (int i = 0; i < arr.length; ++i)
            System.out.print(arr[i]);
    }
}
/*This code is contributed by Rajat Mishra */

Python3

# Python3 program for counting sort

# The main function that sort the given string arr[] in
# alphabetical order


def countSort(arr):

    # The output character array that will have sorted arr
    output = [0 for i in range(len(arr))]

    # Create a count array to store count of individual
    # characters and initialize count array as 0
    count = [0 for i in range(256)]

    # For storing the resulting answer since the
    # string is immutable
    ans = ["" for _ in arr]

    # Store count of each character
    for i in arr:
        count[ord(i)] += 1

    # Change count[i] so that count[i] now contains actual
    # position of this character in output array
    for i in range(256):
        count[i] += count[i-1]

    # Build the output character array
    for i in range(len(arr)):
        output[count[ord(arr[i])]-1] = arr[i]
        count[ord(arr[i])] -= 1

    # Copy the output array to arr, so that arr now
    # contains sorted characters
    for i in range(len(arr)):
        ans[i] = output[i]
    return ans


# Driver code
if __name__ == '__main__':
    arr = "geeksforgeeks"
    ans = countSort(arr)
    print("Sorted character array is % s" % ("".join(ans)))

# This code is contributed by Nikhil Kumar Singh

C#

// C# implementation of Counting Sort
using System;

class GFG {

    static void countsort(char[] arr)
    {
        int n = arr.Length;

        // The output character array that
        // will have sorted arr
        char[] output = new char[n];

        // Create a count array to store
        // count of individual characters
        // and initialize count array as 0
        int[] count = new int[256];

        for (int i = 0; i < 256; ++i)
            count[i] = 0;

        // store count of each character
        for (int i = 0; i < n; ++i)
            ++count[arr[i]];

        // Change count[i] so that count[i]
        // now contains actual position of
        // this character in output array
        for (int i = 1; i <= 255; ++i)
            count[i] += count[i - 1];

        // Build the output character array
        // To make it stable we are operating in reverse
        // order.
        for (int i = n - 1; i >= 0; 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 (int i = 0; i < n; ++i)
            arr[i] = output[i];
    }

    // Driver code
    public static void Main()
    {

        char[] arr = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
                       'r', 'g', 'e', 'e', 'k', 's' };

        countsort(arr);

        Console.Write("Sorted character array is ");
        for (int i = 0; i < arr.Length; ++i)
            Console.Write(arr[i]);
    }
}

// This code is contributed by Sam007.

PHP

<?php
// PHP Program for counting sort

$RANGE = 255;

// The main function that sort 
// the given string arr[] in
// alphabetical order
function countSort($arr)
{
    global $RANGE;
    
    // The output character array 
    // that will have sorted arr
    $output = array(strlen($arr));
    $len = strlen($arr);
    
    // Create a count array to 
    // store count of individual 
    // characters and initialize
    // count array as 0
    $count = array_fill(0, $RANGE + 1, 0);

    // Store count of 
    // each character
    for($i = 0; $i < $len; ++$i)
        ++$count[ord($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
    // To make it stable we are operating 
    // in reverse order.
    for ($i = $len-1; $i >= 0 ; $i--)
    {
        $output[$count[ord($arr[$i])] - 1] = $arr[$i];
        --$count[ord($arr[$i])];
    }

    // Copy the output array to 
    // arr, so that arr now 
    // contains sorted characters
    for ($i = 0; $i < $len; ++$i)
        $arr[$i] = $output[$i];
return $arr;
}

// Driver Code
$arr = "geeksforgeeks"; //"applepp";

$arr = countSort($arr);

echo "Sorted character array is " . $arr;

// This code is contributed by mits
?>

Javascript

Javas<script>

// Javascript implementation of Counting Sort
function sort(arr)
{
    var n = arr.length;

    // The output character array that will have sorted arr
    var output = Array.from({length: n}, (_, i) => 0);

    // Create a count array to store count of individual
    // characters and initialize count array as 0
    var count = Array.from({length: 256}, (_, i) => 0);


    // store count of each character
    for (var i = 0; i < n; ++i)
        ++count[arr[i].charCodeAt(0)];
    // Change count[i] so that count[i] now contains actual
    // position of this character in output array
    for (var i = 1; i <= 255; ++i)
        count[i] += count[i - 1];

    // Build the output character array
    // To make it stable we are operating in reverse order.
    for (var i = n - 1; i >= 0; i--) {
        output[count[arr[i].charCodeAt(0)] - 1] = arr[i];
        --count[arr[i].charCodeAt(0)];
    }

    // Copy the output array to arr, so that arr now
    // contains sorted characters
    for (var i = 0; i < n; ++i)
        arr[i] = output[i];
     return arr;
}

// Driver method
    var arr = [ 'g', 'e', 'e', 'k', 's', 'f', 'o',
                   'r', 'g', 'e', 'e', 'k', 's' ];

    arr = sort(arr);
    document.write("Sorted character array is ");
    for (var i = 0; i < arr.length; ++i)
        document.write(arr[i]);

// This code is contributed by shikhasingrajput
</script>
cript
Output

Sorted character array is eeeefggkkorss

Time Complexity: O(N + K) where N is the number of elements in the input array and K is the range of input. 
Auxiliary Space: O(N + K)

Characteristics of counting sort:

  • Counting sort makes assumptions about the data, for example, it assumes that values are going to be in the range of 0 to 10 or 10 – 99, etc, Some other assumption counting sort makes is input data will be positive integers.
  • Like other algorithms this sorting algorithm is not a comparison-based algorithm, it hashes the value in a temporary count array and uses them for sorting.
  • It uses a temporary array making it a non-In Place algorithm.

Important points:

  • Counting sort is efficient if the range of input data is not significantly greater than the number of objects to be sorted. Consider the situation where the input sequence is between the range 1 to 10K and the data is 10, 5, 10K, 5K. 
  • It is not a comparison-based sorting. Its running time complexity is O(n) with space proportional to the range of data. 
  • Counting sorting is able to achieve this because we are making assumptions about the data we are sorting.
  • It is often used as a sub-routine to another sorting algorithm like the radix sort. 
  • Counting sort uses partial hashing to count the occurrence of the data object in O(1).
  • The counting sort can be extended to work for negative inputs also.
  • Counting sort is a stable algorithm. But it can be made stable with some code changes.

Last Updated : 09 Jun, 2023
Like Article
Save Article
Similar Reads
Related Tutorials