Implementing Counting Sort using map in C++ Last Updated : 12 Jul, 2025 Comments Improve Suggest changes 2 Likes Like Report 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: A data structure which occupies the space for input elements only and not for all the elements other than inputs.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) Comment R Rg Prasad Follow 2 Improve R Rg Prasad Follow 2 Improve Article Tags : C++ cpp-map counting-sort Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like