Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- static bool cmp(pair<int, int>& a,
- pair<int, int>& b)
- {
- if (a.second == b.second) {
- return a.first < b.first; // Sort by u.first in ascending order if frequencies are the same.
- }
- return a.second > b.second;
- }
- int main() {
- //code
- int t;
- cin>>t;
- while(t--)
- {
- int n;
- cin>>n;
- vector<int> arr(n);
- map<int,int> m;
- for(int i=0;i<n;i++)
- {
- cin>>arr[i];
- m[arr[i]]++;
- }
- vector<pair<int, int> > A;
- for (auto& it : m) {
- A.push_back(it);
- }
- sort(A.begin(), A.end(), cmp);
- vector<int> v;
- for(auto u:A)
- {
- for(int i=0;i<u.second;i++)
- {
- v.push_back(u.first);
- }
- }
- for(int i=0;i<v.size();i++)
- {
- cout<<v[i]<<" ";
- }
- cout<<endl;
- }
- return 0;
- }
- // https://practice.geeksforgeeks.org/problems/sorting-elements-of-an-array-by-frequency/
Advertisement
Add Comment
Please, Sign In to add comment