fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. bool cmp(pair<int, int> a, pair<int, int> b) {
  6. if(a.second == b.second) {
  7. return a.first < b.first;
  8. }
  9.  
  10. return a.second > b.second;
  11. }
  12.  
  13. void sortByFreq(int a[], int n) {
  14.  
  15. unordered_map<int, int> m;
  16.  
  17. for(int i = 0; i < n; i++) {
  18. m[a[i]]++;
  19. }
  20. vector<pair<int, int>> v;
  21. unordered_map<int, int> :: iterator it;
  22. for(auto it: m) {
  23. // cout<<it->first<<" "<<it->second<<endl;
  24. v.push_back({it.first, it.second});
  25. }
  26. for(int i = 0; i < v.size(); i++) {
  27.  
  28. cout<<v[i].first<<" " ;
  29. }
  30. cout<<endl;
  31. sort(v.begin(), v.end(), cmp);
  32.  
  33. for(auto i : v) {
  34. int s = i.second;
  35. while(s > 0) {
  36. cout<<i.first<<" " ;
  37. s--;
  38. }
  39.  
  40. }
  41.  
  42. }
  43.  
  44. int main() {
  45. int a[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
  46. int n = sizeof(a) / sizeof(a[0]);
  47. sortByFreq(a, n);
  48. return 0;
  49. }
Success #stdin #stdout 0s 4892KB
stdin
Standard input is empty
stdout
8   5   -1   2   6   9999999   
8   8   8   2   2   5   5   -1   6   9999999