-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathsort_elements_of_array_by_freq.cpp
79 lines (61 loc) · 1.43 KB
/
sort_elements_of_array_by_freq.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Given an array 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.
*/
#include <bits/stdc++.h>
using namespace std;
vector<int> sortByFreq(int arr[], int n);
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int a[n + 1];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
vector<int> v;
v = sortByFreq(a, n);
for (int i : v)
cout << i << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends
//Complete this function
//Return the sorted array
bool sortbysec(pair<int, int> a, pair<int, int> b)
{
if (a.second != b.second)
return (a.second > b.second);
else
return (a.first < b.first);
}
vector<int> sortByFreq(int arr[], int n)
{
//Your code here
map<int, int, greater<int>> mp;
vector<int> res;
for (int i = 0; i < n; i++)
{
mp[arr[i]]++;
}
vector<pair<int, int>> v;
for (auto it = mp.begin(); it != mp.end(); it++)
v.push_back(make_pair(it->first, it->second));
sort(v.begin(), v.end(), sortbysec);
for (auto it = v.begin(); it != v.end(); it++)
{
int k = it->second;
while (k--)
{
res.push_back(it->first);
}
}
return res;
}