Open In App

C++ Program For Counting Sort

Counting Sort is a sorting technique in which the array is sorted according to the keys between some specific ranges. It is not a comparison sort because we do not sort the elements of the array by comparing them with other elements. In counting sort, we determine the position of each element in the array just by counting the frequency of each distinct element in the array and then applying prefix sum to the count to find the position of each element in the sorted array.

Algorithm of Counting Sort

In counting sort, we count the frequency of the elements in the array and then using some mathematics, we find the sorted position of the elements.



  1. Let arr[] = {a1, a2, a3 …, an};
  2. Inside countingSort, declare count[largest_num]
  3. Store the frequency of each element in the count array at index count[number].
  4. Calculate the prefix sum of count array.
  5. Declare result[n].
  6. For each element in arr, its sorted index in result will be –count[number].
  7. Copy result[] to arr[]

Working of Counting Sort in C++

Let’s consider an array of integers arr[] = {2, 3, 0, 0, 1, 2, 1, 3, 3, 1}.

Original Array arr[]

First, we will find the maximum element from the array which is 3 in this example.



Here, value of n (no. of elements) = 10 and k = 3.

Now, we will take another array for counting the frequency of each element in the array. The size of this array will be the range of values in the original array + 1 i.e. , k + 1. We will initialize the array by 0 initially and then update the array. Let us name the array as count.

count[] Array

Now, we will count the frequency of each distinct element from the original array and then update the values in count array.

count[] Array after Counting

Now, after updating the count array , we perform prefix sum and then put them in the count array. The prefix sum is performed in such a way that – (element at index i + element at index i-1) gives element at index i in the count array i.e., for e.g., count[1] = count[0] + count[1].

Prefix Sum in count[] Array

Now, we take a separate array named answer array of size n. Here, we store the final elements after sorting them.

The final elements in the array are filled by checking the original array. We start traversing the original array from the end and then we go to that index of the Updated count array i.e., if the value of the 10th or last index of the original array is 9 , then we go to the Updated count[9] and then find the value in it.

Whatever the value of that position in count array be, we decrement the value by 1 and then place the element (i.e.,9 as per the example stated here) in that decremented position of the answer array. We decrement the value by 1 since our arrays are 0-based indexing arrays.

Counting Sort in C++

In the above diagram, we consider a variable ‘i’ for traversing through the original array. In the diagram, we can see that the value of i decreases as we are traversing from the opposite direction of the original array.

First, for a certain index supposing 9 which is the last index of the original array, the value of i is 9. Then we find the original array[9] which is equal to 1. We then move to the count array and search for index 1. In index 1 of the count array initially, the value was 5 as could be seen from the diagram. We decrement the value 5 by 1 as we are going to fill our answer on a 0-based indexing array. Thus, the value becomes 4. Now, in the answer array we find the index 4 and place original array[9] which is 1 in the 4th index of the answer array.

This continues till the value of i is less than or equal to 0.

At the end, we get the answer array and we copy it to the original array.

C++ Program for Counting Sort




// C++ Program to implement counting sort
#include <bits/stdc++.h>
using namespace std;
  
// counting sort function
void count_sort(int arr[], int n)
{
    // max_element() is a c++ stl function to find the
    // maximum element from an array
    int k = *max_element(arr, arr + n);
  
    // we declare a count array and initialize the array by
    // 0
    int count[k + 1] = { 0 };
  
    // we count the frequency of each distinct element in
    // the original array
    for (int i = 0; i < n; i++) {
        count[arr[i]]++;
    }
  
    // we perform prefix sum and update the count array
    for (int i = 1; i <= k; i++) {
        count[i] = count[i] + count[i - 1];
    }
  
    // we store our answer in the ans array
    int ans[n];
    for (int i = n - 1; i >= 0; i--) {
        ans[--count[arr[i]]] = arr[i];
    }
  
    // here we copy the contents on ans array to our
    // original array
    for (int i = 0; i < n; i++) {
        arr[i] = ans[i];
    }
}
  
// driver code
int main()
{
    int arr[] = { 1, 3, 7, 0, 1, 1, 6, 3, 0, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    count_sort(arr, n);
  
    // displaying the result
    cout << "Array after performing count sort : " << endl;
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

Output
Array after performing count sort : 
0 0 1 1 1 3 3 3 6 7 

Complexity Analysis of Counting Sort

Time Complexity

Space Complexity

Advantages of Counting Sort

The counting sort algorithm has the following benefits over other sorting algorithms:

Limitations of Counting Sort


Article Tags :