C++ Program to Implement Counting Sort



Counting sort is a stable and non-comparison-based sorting technique, that is used to sort the objects according to the keys that are small integers. It counts the number of keys whose key values are same. It works by counting the occurrences of elements in the array. This sorting technique is efficient when difference between different keys are not so big, otherwise it can increase the space complexity.

In this article, we have an unsorted array. Our task is to implement the counting sort algorithm to sort the given unsorted array in C++.

Example

Here is an example of counting sort algorithm to sort the given array.

Input:
arr = {4, 2, 2, 8, 3, 3, 1}

Output:
Array after Sorting: 1 2 2 3 3 4 8 

The explanation of the above example to sort the given array using counting sort is as follows:

Maximum element = 8

count[] array up to 8 initially with 0 count:
[0, 0, 0, 0, 0, 0, 0, 0, 0] => count
[0, 1, 2, 3, 4, 5, 6, 7, 8] => elements

Count the frequency of elements in the original given array:
[0, 1, 2, 2, 1, 0, 0, 0, 1] => count
[0, 1, 2, 3, 4, 5, 6, 7, 8] => elements

Calculating cumulative sum of count:
[0, 1, 3, 5, 6, 6, 6, 6, 7] => count
[0, 1, 2, 3, 4, 5, 6, 7, 8] => elements

Use count[array[i]] - 1 to get the correct index of the elements:
Sorted array:
[1, 2, 2, 3, 3, 4, 8]

Steps to Implement Counting Sort

The steps to implement the counting sort algorithm is as follows:

  • First, we find the maximum element of the array. We have used the getMax() function where we have compared the first element of array with all the elements to get the maximum element in the array.
  • Then we have used a count[] array of size max+1 to 0.
  • The count[] array stores the count of occurrences of elements of the input array. Using this count, we calculate the cumulative count of the elements.
  • Then, using the cumulative count of the elements, we build an output[] array.
  • We have Used output[count[array[i]] - 1] to get the correct sorted position of each element of the input array.
  • To get the correct position of elements, we have traversed the array from right to left. This helps to get the correct position of duplicate elements.
  • Then we have copied back the sorted elements present in the output[] array to the input array arr.

C++ program to Implement Counting Sort

Here is the C++ code implementation of the above steps for counting sort algorithm.

#include <iostream>
#include <vector>
using namespace std;

void display(const vector<int>& array) {
    for (int num : array)
        cout << num << " ";
    cout << endl;
}

// To get maximum value 
int getMax(const vector<int>& array) {
    int max = array[0];
    for (int i = 1; i < array.size(); i++) {
        if (array[i] > max)
            max = array[i];
    }
    return max;
}

// Function to implement Count Sort
void countSort(vector<int>& array) {
    int size = array.size();
    int max = getMax(array); 

    vector<int> count(max + 1, 0);   
    vector<int> output(size);        

    // Counting each element
    for (int i = 0; i < size; i++)
        count[array[i]]++;

    // Cumulative sum of count
    for (int i = 1; i <= max; i++)
        count[i] += count[i - 1];

    // Output array 
    for (int i = size - 1; i >= 0; i--) {
        output[count[array[i]] - 1] = array[i];
        count[array[i]]--;
    }

    array = output;
}

int main() {
    vector<int> arr = {4, 2, 2, 8, 3, 3, 1};

    cout << "Array before Sorting: ";
    display(arr);

    countSort(arr); 

    cout << "Array after Sorting: ";
    display(arr);

    return 0;
}

The output of the above code is given below:

Array before Sorting: 4 2 2 8 3 3 1 
Array after Sorting: 1 2 2 3 3 4 8 

Complexity of Counting Sorting Algorithm

Updated on: 2025-05-07T18:37:09+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements