Skip to content

Instantly share code, notes, and snippets.

@Ch-sriram
Last active July 9, 2020 13:54
Show Gist options
  • Save Ch-sriram/836d9a0519c5be44e3f20b9cefba084a to your computer and use it in GitHub Desktop.
Save Ch-sriram/836d9a0519c5be44e3f20b9cefba084a to your computer and use it in GitHub Desktop.
Sorting elements of an Array by Frequency aka Frequency Sort.
// Problem link: https://practice.geeksforgeeks.org/problems/sorting-elements-of-an-array-by-frequency/0/
#include <vector>
#include <climits>
#include <iostream>
#include <algorithm>
using namespace std;
#define ull uint64_t
void frequency_sort(int n, int m = 1, int M = 60) {
vector<vector<int>> count(M-m+1, vector<int>(2, 0));
for(ull i = 0; i < count.size(); ++i)
count[i][0] = i+m;
int x;
for(int i = 0; i < n; ++i) {
cin >> x;
count[x-m][1]++;
}
int max_freq = 0;
vector<vector<int>> real_count;
for(ull i = 0; i < count.size(); ++i)
if(count[i][1]) {
vector<int> temp{count[i][0], count[i][1]};
real_count.push_back(temp);
max_freq = max(max_freq, count[i][1]);
}
for(int k = max_freq; k >= 1; --k)
for(ull i = 0; i < real_count.size(); ++i)
if(real_count[i][1] == k)
for(int j = 0; j < k; ++j)
cout << real_count[i][0] << " ";
cout << endl;
}
int main() {
int t; cin >> t;
while(t--) {
int n; cin >> n;
frequency_sort(n);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment