Sort by Set Bit Count | Practice | GeeksforGeeks

Given an array of integers, sort the array (in descending order) according to count of set bits in binary representation of array elements.  
Note: For integers having same number of set bits in their binary representation, sort according to their position in the original array i.e., a stable sort.
Input: 
arr[] = {5, 2, 3, 9, 4, 6, 7, 15, 32};
Output:
15 7 5 3 9 6 2 4 32
Explanation:
The integers in their binary
representation are:
15 - 1111
7  - 0111
5  - 0101
3  - 0011
9  - 1001
6  - 0110
2  - 0010
4  - 0100
32 - 10000
hence the non-increasing sorted order is:
{15}, {7}, {5, 3, 9, 6}, {2, 4, 32}
Input: 
arr[] = {1, 2, 3, 4, 5, 6};
Output: 
3 5 6 1 2 4
Explanation:
3  - 0011
5  - 0101
6  - 0110
1  - 0001
2  - 0010
4  - 0100
hence the non-increasing sorted order is
{3, 5, 6}, {1, 2, 4}


Your Task:
You don't need to print anything, printing is done by the driver code itself. You just need to complete the function sortBySetBitCount() which takes the array arr[] and its size N as inputs and sort the array arr[] inplace. Use of extra space is prohibited.
 
Expected Time Complexity: O(N.log(N))
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ N ≤ 105
1 ≤ A[i] ≤ 106 
+2
harendraseervi1234567893 weeks ago
Using __builtin_popcount(x) funtion in c++
void sortBySetBitCount(int arr[], int n)
   {
       int maxi=INT_MIN;
       for(int i=0;i<n;i++){
        maxi=max(maxi,__builtin_popcount(arr[i]));
       }
       vector<int>a[maxi+1];
       for(int i=0;i<n;i++){
           a[__builtin_popcount(arr[i])].push_back(arr[i]);
       }
       int k=0;
       for(int i=maxi;i>=0;i--){
           for(auto val:a[i]){
               arr[k]=val;
               k++;
           }
       }
   }
+1
wjonesusna20122 months ago
I find it very interesting that my original comparator ends up being too slow. What I started with in python was the below. Surprisingly this was too slow to actually work. Had to switch to bin(num).count('1') to actually make this run in time. I would have thought the binary shift and the binary and would have been faster.
 
def getOneBits(num):
	count = 0
	while(num != 0):
		count += num & 1
		num = num >> 1
	return count
+2
user_4na02 months ago
class Solution{
    public:
    int CountSetBits(int n)
    {
        int cnt = 0;
        while(n)
        {
            n = n & (n-1);
            cnt++;
        }
        return cnt;
    }
    static bool cmp(pair<int,int>a,pair<int,int>b)
    {
       return a.second > b.second;
    }
    void sortBySetBitCount(int arr[], int n)
    {
        vector<pair<int,int>>ans;
        for(int i = 0;i<n;i++)
        {
            int x = CountSetBits(arr[i]);
            ans.push_back({arr[i],x});
        }
        stable_sort(ans.begin(),ans.end(),cmp);
        for(int i = 0;i<n;i++)
        {
            arr[i] = ans[i].first;
        }
    }
};
+5
yashgoswami20002 months ago
class Compute  
{ 
   static void sortBySetBitCount(Integer arr[], int n)
   { 
      Arrays.sort(arr,(a,b)->Integer.compare(Integer.bitCount(b),Integer.bitCount(a)));
      
   } 
}
+2
kashutosh7272 months ago
Can someone please explain where i uses simple sorting  i m getting wrong answer of test case 60  but when  i change  sort to stable_sort it passed all the test cases
 
 int count(int n)
    {
        int c=0;
        while(n>0)
        {
              n = n & (n - 1);
              c++;
        }
        return c;
        
    }
    
    static bool cmp(pair<int,int>v1,pair<int,int>v2)
    {
        int x=(v1.first);
        int y=(v2.first);
        if(x==y)
        {
            return x<y;
        }
        return v1.first>v2.first;
    }
    void sortBySetBitCount(int arr[], int n)
    {
        // Your code goes here
      vector<pair<int,int>>v;
        for(int i=0;i<n;i++)
        {
            int x=count(arr[i]);
           // cout<<x;
          // cout<<count(15);
            v.push_back({x,arr[i]});
        }
        sort(v.begin(),v.end(),cmp);
        for(int i=0;i<n;i++)
        {
            arr[i]=v[i].second;
        }
    }
    
};
//correct code by changing sort to stable sort
        stable_sort(v.begin(),v.end(),cmp);
 
0
kaalel2 months ago
Java Implementation → Using Comparator Interface. No extra space used.
class Compaired implements Comparator<Integer> {
    public static int countSetBits(int n) {
        int result = 0;
        while (n > 0) {
            n = n & (n - 1);
            result++;
        }
        return result;
    }
    
    @Override
    public int compare(Integer o1, Integer o2) {
        return countSetBits(o2) - countSetBits(o1);
    }
}
class Compute  
{ 
    public static void sortBySetBitCount(Integer arr[], int n) {
        Arrays.sort(arr, new Compaired());
    }
}
+1
vaibhavpatidar130520022 months ago
def sortBySetBitCount(self, arr, n):       # Your code goes here       for i in range(n):           arr[i] = bin(arr[i])[2:]       arr.sort(key = lambda x:x.count('1'),reverse=True)       for i in range(n):           arr[i] = int(arr[i],2)       return arr
0
saiudaykiranshinagam2 months ago
  static bool cmp(pair<int,int> a, pair<int,int> b)   {       int cnt1 = __builtin_popcount(a.first);       int cnt2 = __builtin_popcount(b.first);       if(cnt1 == cnt2) return a.second < b.second;       return cnt1 > cnt2;   }      void sortBySetBitCount(int arr[], int n)   {       vector<pair<int,int>> v(n);       for(int i=0;i<n;i++) v[i] = {arr[i],i};              sort(v.begin(),v.end(),cmp);       for(int i=0;i<n;i++) arr[i] = v[i].first;   }
0
2019ucp13942 months ago
Onle line Python3 Solution:
def sortBySetBitCount(self, l, n):
        # Your code goes here
        l.sort(reverse=True,key=lambda x:bin(x).count('1'))
0
rishabhbhatnagar2 months ago
Simple python3 solution:
from functools import lru_cache

@lru_cache(maxsize=None)
def count_bits(n):
    if n == 0:
        return 0 
    return int(n & 1) + count_bits(n >> 1)

class Solution:
    def sortBySetBitCount(self, arr, n):
        arr.sort(key=count_bits, reverse=True)

We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.