Sorting Elements of an Array by Frequency  | Practice | GeeksforGeeks

Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher frequency come first. If frequencies of two elements are same, then smaller number comes first.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
For each testcase, in a new line, print each sorted array in a seperate line. For each array its numbers should be seperated by space.
Constraints:
1 ≤ T ≤ 70
30 ≤ N ≤ 130
1 ≤ Ai ≤ 60 
Example:
Input:
2
5
5 5 4 6 4
5
9 9 9 2 5
Output:
4 4 5 5 6
9 9 9 2 5
Explanation:
Testcase1: The highest frequency here is 2. Both 5 and 4 have that frequency. Now since the frequencies are same then smaller element comes first. So 4 4 comes first then comes 5 5. Finally comes 6.
The output is 4 4 5 5 6.
Testcase2: The highest frequency here is 3. The element 9 has the highest frequency. So 9 9 9 comes first. Now both 2 and 5 have same frequency. So we print smaller element first.
The output is 9 9 9 2 5.
 
0
sharmishtha20001 week ago
def sortArray(arr):   counter = {}   for i in range(len(arr)):       if arr[i] not in counter:           counter[arr[i]] = 1       else:           counter[arr[i]] += 1   arr.sort(key = lambda x: (-counter[x], x))   return arr   k = int(input())for i in range(k):   n = int(input())   arr = list(map(int, input().strip().split()))[:n]   arr = sortArray(arr)   print(*arr)
0
sharmishtha20001 week ago
def sortArray(arr):
    counter = {}
    for i in range(len(arr)):
        if arr[i] not in counter:
            counter[arr[i]] = 1
        else:
            counter[arr[i]] += 1
    arr.sort(key = lambda x: (-counter[x], x))
    return arr
    
k = int(input())
for i in range(k):
    n = int(input())
    arr = list(map(int, input().strip().split()))[:n]
    arr = sortArray(arr)
    print(*arr)
0
sagrikasoni2 weeks ago
JAVA CODE from Scratch

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
   static void  sortFrequency(int []nums){
        HashMap<Integer,Integer> hs = new HashMap<Integer,Integer>();
        for(int i =0;i<nums.length;i++)
        hs.put(nums[i], hs.getOrDefault(nums[i],0)+1);
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a,b)-> {
            if(hs.get(a)==hs.get(b)) return a-b;
            else return hs.get(b)-hs.get(a);
        });
        for(int n: hs.keySet())
        pq.add(n);
        while(pq.size()>0){
            int freq = pq.poll();
            for(int i =0;i<hs.get(freq);i++){
                System.out.print(freq + " ");
            }
            
        }
    }
	public static void main (String[] args) {
	  
       Scanner sc = new Scanner(System.in);
       int t = sc.nextInt();
       while(t-->0){
           int n = sc.nextInt();
             int [] arr = new int[n];
             for(int i =0;i<n;i++)
             arr[i] = sc.nextInt();
             
             sortFrequency(arr);
             System.out.println();
       }
	}
}
+1
wolfofsv2 weeks ago
simple solution:
#include <bits/stdc++.h>
using namespace std;

int main() {
	int t;
	cin>>t;
	while(t--){
	    unordered_map<int, int>mp;
	    int n;
	    cin>>n;
	    int arr[n];
	    for(int i = 0; i < n; i++){
	        int num;
	        cin>>num;
	        mp[num]++;
	        arr[i] = num;
	    }
	    sort(arr, arr + n, [&mp](int a, int b){
	        return mp[a] > mp[b] || (mp[a] == mp[b] && a < b);
	    });
	    for(int i = 0; i < n; i++){
	        cout<<arr[i]<<' ';
	    }
	    cout<<'\n';
	    
	}
	
	return 0;
}
0
akashdeep471 month ago
Time complexity 0.0ms
#include<bits/stdc++.h>using namespace std;struct cmp {   bool operator() (const pair<int, int> &a, const pair<int, int> &b) {       if(a.first == b.first)           return a.second > b.second;       else           return a.first < b.first;   }};
int main() {int t;cin >> t;while(t--) {    int n;    cin >> n;        vector<int> arr(n);    for(int i=0; i<n; i++)         cin >> arr[i];           priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> pq;    unordered_map<int, int> mp;    vector<int> res;        for(auto i : arr)        mp[i]++;            for(auto x : mp) {        pq.push({x.second, x.first});    }        while(pq.size() > 0) {        int freq = pq.top().first;        int value = pq.top().second;        for(int i=0; i<freq; i++) {            res.push_back(value);        }        pq.pop();    }        for(int i=0; i<res.size(); i++) {        cout << res[i] << " ";    }    cout << endl;}return 0;}
0
2019kucp10341 month ago
#include<iostream>
#include<vector>
#include<queue>
#include<unordered_map>
#include<algorithm>
using namespace std;
void fun(){
   unsigned short N;
   vector<pair<int,int>> maxH;
   cin>>N;
   unordered_map<int,int>mpp;
   vector<int> a(N);
   int i;
   for(i=0;i<N;i++){
       cin>>a[i];
       mpp[a[i]]++;
   }
   for(auto it:mpp){
       maxH.push_back({it.second,it.first});
   }
   sort(maxH.begin(),maxH.end(),[](auto &a,auto &b){
       return a.first==b.first?a.second<b.second:a.first>b.first;
       });
   i=0;
   while(i<maxH.size()){
       int j=0;
       while(j<maxH[i].first){
           cout<<maxH[i].second<<" ";
           j++;
       }
       i++;
   }
   cout<<endl;
}
int main()
{
//code
unsigned short T;
cin>>T;
while(T--)
    fun();
return 0;
}
0
amishasahu3281 month ago
#include<bits/stdc++.h>
using namespace std;
#define eff ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ll long long 
#define vi vector<int>

vector<int> frequencySort(vector<int>& nums) 
{
        unordered_map<int,int> mp;
        for(int i = 0; i < nums.size(); i++)
            mp[nums[i]]++;
        
        // Using Lamba function to sort
        // Lamda: [&] (parameter) { Expression }
        // Take two elements from nums array and compare their frequency in mp
        // if frequency is not equal return element with higher frequency
        // if equal then return the smaller element
        sort(nums.begin(), nums.end(), [&](int a, int b) -> bool {
           return (mp[a] != mp[b]? mp[a] > mp[b] : a < b);
        });
        
        return nums;
}
int main(){
    eff;
    int t;
    cin>>t;
    while(t--){
          int n;
          cin>>n;
          vector<int> arr(n);
          for(int i = 0; i < n; i++)
                    cin>>arr[i];
          arr = frequencySort(arr);
          for(auto x: arr)
              cout<<x<<" ";
          cout<<endl;
    }
    return 0;
}
0
akashraje1961 month ago
#include <iostream>#include<map>#include<vector>#include <algorithm>using namespace std;
bool comp(pair<int,int> &a,pair<int,int> &b){      if(a.second == b.second)   {       return a.first < b.first;   }   return a.second > b.second;      //return true;   // return (p.second <pp.second);}
vector<pair<int,int>> sortFreq(vector<int> &a1){      map<int,int> mp;      for(auto it: a1){       mp[it]++;   }      vector<pair<int,int>> vec;      for(auto it : mp){       vec.push_back(it);   }      sort(vec.begin(),vec.end(),comp);            return vec;}
int main() {//codeint t,n;cin >> t;while(t>0){    cin >>n ;    vector<int> vec;    for (int i=0;i<n;i++){        int val;        cin>> val;       vec.push_back(val);    }    vector<pair<int,int>> vec2 ;        vec2 = sortFreq (vec);    for(auto it : vec2){        int freq = it.second;        while(freq > 0){           cout<<it.first << " ";           freq--;           }        }        cout<<endl;       t--;                }return 0;}
0
geetamadhurimallidi2 months ago
simple c++ code:#include <iostream>using namespace std;#include<bits/stdc++.h>int main() {//codeint t;cin>>t;while(t--){    int n;    cin>>n;    int a[n];    int b[61]={0};    vector<int>v;    for(int i=0;i<n;i++)    {        cin>>a[i];        b[a[i]]++;    }    while(v.size()<n)    {        int max = INT_MIN,l=0;//each time initialise the max        for(int i=1;i<61;i++)        {           if(b[i]>max)           {             max = b[i];             l=i;           }        }        while(max)        {           v.push_back(l);           max--;        }        b[l] = 0;//reduce the frequency to zero after printing    }    for(int i=0;i<n;i++)    {        cout<<v[i]<<" ";    }    cout<<endl;}return 0;}
0
soumik8673 months ago
#include<iostream>#include<bits/stdc++.h>using namespace std;bool swap_or_not(pair<int,int> a, pair<int,int> b){   if(a.second!=b.second){       if(a.second>b.second) return false;       else return true;   }   else{       if(a.first>b.first) return true;       else return false;   }}int main(){int t;cin>>t;while(t--){    int n;    cin>>n;    int arr[n];    vector<pair<int,int>> v;    unordered_map<int,int> m;    for(int i=0;i<n;i++){        cin>>arr[i];        m[arr[i]]++;    }    for(auto z:m){        if(z.second!=0){            v.push_back({z.first,z.second});        }    }    for(int i=0;i<v.size();i++){        for(int j=i+1;j<v.size();j++){            if(swap_or_not(v[i],v[j])){                swap(v[i],v[j]);            }        }    }    for(int i=0;i<v.size();i++){        int z=v[i].second;        while(z--){            cout<<v[i].first<<" ";        }    }cout<<endl;}return 0;}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.