-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathSorting Elements of an Array by Frequency.cpp
62 lines (49 loc) · 1.25 KB
/
Sorting Elements of an Array 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
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
bool static comp(pair<int ,int> a,pair<int ,int> b){
if(a.first>b.first)
return true;
else if(a.first==b.first and a.second<b.second)
return true;
return false;
}
//Complete this function
//Function to sort the array according to frequency of elements.
vector<int> sortByFreq(int arr[],int n)
{
map< int , int > mp;
for(int i=0;i<n;i++)
mp[arr[i]]+=1;
vector<pair< int,int > > p;
for(auto i :mp){
pair<int,int> a;
a.first=i.second;
a.second=i.first;
p.push_back(a);
}
vector<int> aa;
sort(p.begin(),p.end(),comp);
for(int i=0;i<p.size();i++){
while(p[i].first--)
aa.push_back(p[i].second);
}
return aa;
}
};
int main() {
int n;
cin >> n;
int a[n+1];
for(int i = 0;i<n;i++){
cin >> a[i];
}
Solution obj;
vector<int> v;
v = obj.sortByFreq(a,n);
for(int i:v)
cout<<i<<" ";
cout << endl;
return 0;
}