# Sort an array according to count of set bits in C++

C++Server Side ProgrammingProgramming

Here we will see one interesting problem to sort an array based on the set-bits. When an element in the array has higher number of set-bits, then that will be placed before another element which has lower number of set bits. Suppose some numbers are 12, 15, 7. So the set bits are basically number of 1’s in their binary representation. These are 1100 (12), 1111 (15), and 0111 (7). So after sorting it will be look like this −

1111, 0111, 1100 (15, 7, 12)

Here we have to find the number of set-bits at first. Then we will use the C++ STL sort function to sort them. We have to create the comparison logic based on the set-bit counts

## Algorithm

getSetBitCount(number):
Begin
count := 0
while number is not 0, do
if number AND 1 = 1, then
increase count by 1
number = right shift number by one bit
done
return count
End
compare(num1, num2):
Begin
count1 = getSetBitCount(num1)
count2 = getSetBitCount(num2)
if count1 <= count2, then return false, otherwise return true
End

## Example

Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
int getSetBitCount(int number){
int count = 0;
while(number){
if(number & 1 == 1)
count++;
number = number >> 1 ; //right shift the number by one bit
}
return count;
}
int compare(int num1, int num2){
int count1 = getSetBitCount(num1);
int count2 = getSetBitCount(num2);
if(count1 <= count2)
return 0;
return 1;
}
main(){
int data[] = {2, 9, 4, 3, 5, 7, 15, 6, 8};
int n = sizeof(data)/sizeof(data);
sort(data, data + n, compare);
for(int i = 0; i<n; i++){
cout << data[i] << " ";
}
}

## Output

15 7 9 3 5 6 2 4 8