From b2f7bcd0a7f1d140a628af52321f710040e2a8af Mon Sep 17 00:00:00 2001 From: Udhay <72250606+Udhay-Brahmi@users.noreply.github.com> Date: Wed, 23 Dec 2020 07:57:19 +0530 Subject: [PATCH] Create Sort by Set Bit Count --- Sort by Set Bit Count | 76 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Sort by Set Bit Count diff --git a/Sort by Set Bit Count b/Sort by Set Bit Count new file mode 100644 index 0000000..9db3dae --- /dev/null +++ b/Sort by Set Bit Count @@ -0,0 +1,76 @@ +// { Driver Code Starts +#include +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>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