-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathSort by Set Bit Count
More file actions
76 lines (69 loc) · 1.26 KB
/
Sort by Set Bit Count
File metadata and controls
76 lines (69 loc) · 1.26 KB
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
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
This question is now solved.......................
/*
bool compare(int a,int b){
int ca=0,cb=0;
while(a){
if(a&1)ca++;
a=a>>1;
}
while(b){
if(b&1)cb++;
b=b>>1;
}
return ca>cb;
}
*/
int countBits(int a)
{
int count = 0;
while (a) {
if (a & 1)
count += 1;
a = a >> 1;
}
return count;
}
// custom comparator of std::sort
int cmp(int a, int b)
{
int count1 = countBits(a);
int count2 = countBits(b);
// this takes care of the stability of
// sorting algorithm too
if (count1 <= count2)
return false;
return true;
}
class Solution{
public:
void sortBySetBitCount(int arr[], int n)
{
// Your code goes here
stable_sort(arr,arr+n,cmp);
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
Solution ob;
ob.sortBySetBitCount(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends