forked from s7917/Hacktoberfest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSort elements by frequency.cpp
63 lines (45 loc) · 1.06 KB
/
Sort elements by frequency.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
#include <bits/stdc++.h>
using namespace std;
// Used for sorting by frequency. And if frequency is same,
// then by appearance
bool sortByVal(const pair<int, int>& a,
const pair<int, int>& b)
{
// If frequency is same then sort by index
if (a.second == b.second)
return a.first < b.first;
return a.second > b.second;
}
// function to sort elements by frequency
vector<int>sortByFreq(int a[], int n)
{
vector<int>res;
unordered_map<int, int> m;
vector<pair<int, int> > v;
for (int i = 0; i < n; ++i) {
// Map m is used to keep track of count
// of elements in array
m[a[i]]++;
}
// Copy map to vector
copy(m.begin(), m.end(), back_inserter(v));
// Sort the element of array by frequency
sort(v.begin(), v.end(), sortByVal);
for (int i = 0; i < v.size(); ++i)
while(v[i].second--)
{
res.push_back(v[i].first);
}
return res;
}
// Driver program
int main()
{
int a[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
int n = sizeof(a) / sizeof(a[0]);
vector<int>res;
res = sortByFreq(a, n);
for(int i = 0;i < res.size(); i++)
cout<<res[i]<<" ";
return 0;
}