jayati

Sorting Elements of an Array by Frequency

Sep 3rd, 2023
868
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1.  
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. static bool cmp(pair<int, int>& a,
  6.         pair<int, int>& b)
  7. {
  8.     if (a.second == b.second) {
  9.         return a.first < b.first; // Sort by u.first in ascending order if frequencies are the same.
  10.     }
  11.     return a.second > b.second;
  12. }
  13.  
  14. int main() {
  15.     //code
  16.     int t;
  17.     cin>>t;
  18.     while(t--)
  19.     {
  20.         int n;
  21.         cin>>n;
  22.         vector<int> arr(n);
  23.         map<int,int> m;
  24.         for(int i=0;i<n;i++)
  25.         {
  26.             cin>>arr[i];
  27.             m[arr[i]]++;
  28.         }
  29.           vector<pair<int, int> > A;
  30.  
  31.     for (auto& it : m) {
  32.         A.push_back(it);
  33.     }
  34.  
  35.         sort(A.begin(), A.end(), cmp);
  36.         vector<int> v;
  37.         for(auto u:A)
  38.         {
  39.             for(int i=0;i<u.second;i++)
  40.             {
  41.                 v.push_back(u.first);
  42.             }
  43.         }
  44.         for(int i=0;i<v.size();i++)
  45.         {
  46.             cout<<v[i]<<" ";
  47.         }
  48.         cout<<endl;
  49.        
  50.     }
  51.     return 0;
  52. }
  53. // https://practice.geeksforgeeks.org/problems/sorting-elements-of-an-array-by-frequency/
Advertisement
Add Comment
Please, Sign In to add comment