Skip to content

Commit 65cfd94

Browse files
Create sort_elements_by_frequency.cpp
1 parent d8ce3f9 commit 65cfd94

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

Diff for: Hashing/sort_elements_by_frequency.cpp

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// Given an array of integers, sort the array according to frequency of elements.
2+
// That is elements that have higher frequency come first. If frequencies of two elements are same, then smaller number comes first.
3+
// Input:
4+
// N = 5
5+
// A[] = {5,5,4,6,4}
6+
// Output: 4 4 5 5 6
7+
8+
class Solution{
9+
public:
10+
11+
//custom comparator function to sort map according to frequencies
12+
static bool cmp( pair<int, int> &a, pair<int, int> &b)
13+
{
14+
if(a.second==b.second)
15+
return a.first<b.first;
16+
return a.second>b.second;
17+
}
18+
19+
vector<int> sortByFreq(int arr[],int n)
20+
{
21+
22+
vector<int>ans;
23+
map<int,int> m;
24+
vector<pair<int, int> > A;
25+
26+
//storing the elements as keys and counting its frequency
27+
for(int i=0; i<n; i++)
28+
{
29+
int x= arr[i];
30+
m[x]++;
31+
}
32+
33+
// Copy key-value pair from Map
34+
// to vector of pairs
35+
for (auto &it : m) {
36+
A.push_back(it);
37+
}
38+
39+
//sorting the vector of pairs using cmp function
40+
sort(A.begin(), A.end(), cmp) ;
41+
42+
for(auto x: A)
43+
{
44+
//printing the element the no. of times it occured in the actual array
45+
while(x.second)
46+
{
47+
ans.push_back(x.first);
48+
x.second--;
49+
}
50+
51+
}
52+
53+
return ans;
54+
}
55+
};
56+
57+
int main() {
58+
59+
int t;
60+
cin >> t;
61+
62+
while(t--){
63+
64+
int n;
65+
cin >> n;
66+
67+
int a[n+1];
68+
69+
for(int i = 0;i<n;i++){
70+
cin >> a[i];
71+
}
72+
Solution obj;
73+
vector<int> v;
74+
v = obj.sortByFreq(a,n);
75+
for(int i:v)
76+
cout<<i<<" ";
77+
cout << endl;
78+
}
79+
80+
return 0;
81+
}

0 commit comments

Comments
 (0)