VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-elements-by-frequency-using-stl/

⇱ Sort elements by frequency using STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort elements by frequency using STL

Last Updated : 10 Apr, 2023

Given an array of integers, sort the array according to frequency of elements. If frequencies of two elements are same, print them in increasing order. Examples:

Input : arr[] = {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}
Output : 3 3 3 3 2 2 2 12 12 4 5
Explanation :
No. Freq
2 : 3
3 : 4
4 : 1
5 : 1
12 : 2

We have discussed different approaches in below posts : Sort elements by frequency | Set 1 Sort elements by frequency | Set 2 We can solve this problem using map and pairs. Initially we create a map such that map[element] = freq. Once we are done building the map, we create an array of pairs. A pair which stores elements and their corresponding frequency will be used for the purpose of sorting. We write a custom compare function which compares two pairs firstly on the basis of freq and if there is a tie on the basis of values. 

Below is its c++ implementation : 


Output
Elements sorted by frequency are: 3 3 3 3 2 2 2 12 12 4 5 

Time Complexity : O(n Log n) 

Space Complexity: O(n)
The above algorithm requires O(n) space for the hash map and the array of pairs.

Comment