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> usingnamespacestd; // Function to sort the array using counting sort voidcountingSort(vector<int> arr, intn) {     // Map to store the frequency     // of the array elements     map<int, int> freqMap;     for(autoi = arr.begin(); i != arr.end(); i++) {         freqMap[*i]++;     }     inti = 0;     // For every element of the map     for(autoit : freqMap) {         // Value of the element         intval = it.first;         // Its frequency         intfreq = it.second;         for(intj = 0; j < freq; j++)             arr[i++] = val;     }     // Print the sorted array     for(autoi = arr.begin(); i != arr.end(); i++) {         cout << *i << " ";     } } // Driver code intmain() {     vector<int> arr = { 1, 4, 3, 5, 1 };     intn = arr.size();     countingSort(arr, n);     return0; }  | 
1 1 3 4 5
Time Complexity: O(n log(n))
Auxiliary Space: O(n)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    







