Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Sort by Set Bit Count #24

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions Sort by Set Bit Count
Original file line number Diff line number Diff line change
@@ -0,0 +1,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