Last active
July 9, 2020 13:54
Sorting elements of an Array by Frequency aka Frequency Sort.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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