Friday, September 5, 2025
HomeData Modelling & AIImplementing Counting Sort using map in C++

Implementing Counting Sort using map in C++

Counting Sort is one of the best sorting algorithms which can sort in O(n) time complexity but the disadvantage with the counting sort is it’s space complexity, for a small collection of values, it will also require a huge amount of unused space. So, we need two things to overcome this:

  1. A data structure which occupies the space for input elements only and not for all the elements other than inputs.
  2. The stored elements must be in sorted order because if it’s unsorted then storing them will be of no use.

So Map in C++ satisfies both the condition. Thus we can achieve this through a map. 

Examples:

Input: arr[] = {1, 4, 3, 5, 1} 

Output: 1 1 3 4 5 

Input: arr[] = {1, -1, -3, 8, -3} 

Output: -3 -3 -1 1 8

Below is the implementation of Counting Sort using map in C++: 

CPP




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort the array using counting sort
void countingSort(vector<int> arr, int n)
{
 
    // Map to store the frequency
    // of the array elements
    map<int, int> freqMap;
    for (auto i = arr.begin(); i != arr.end(); i++) {
        freqMap[*i]++;
    }
 
    int i = 0;
 
    // For every element of the map
    for (auto it : freqMap) {
 
        // Value of the element
        int val = it.first;
 
        // Its frequency
        int freq = it.second;
        for (int j = 0; j < freq; j++)
            arr[i++] = val;
    }
 
    // Print the sorted array
    for (auto i = arr.begin(); i != arr.end(); i++) {
        cout << *i << " ";
    }
}
 
// Driver code
int main()
{
    vector<int> arr = { 1, 4, 3, 5, 1 };
    int n = arr.size();
 
    countingSort(arr, n);
 
    return 0;
}


Output:

1 1 3 4 5

Time Complexity: O(n log(n))

Auxiliary Space: O(n)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32265 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS