![]() |
VOOZH | about |
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.
Examples:
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 - 100000
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: The integers in their binary representation are:
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}.
Table of Content
The idea is to use the inbuilt sort function and custom comparator to sort the array according to set-bit count.
Dry run for arr[] = [5, 4, 7, 15] :
Final output: 15 7 5 4
15 7 5 3 9 6 2 4 32
The idea is to use counting sort to arrange the elements in descending order of count of set-bits. For any integer, assuming the minimum and maximum set-bits can be 1 and 31 respectively, create an array count[][] of size 32, where each element count[i] stores the elements of given array with count of their set bits equal to i. After inserting all the elements, traverse count[][] in reverse order, and store the elements at each index in the given array.
Dry run for arr[] = [5, 4, 7, 15] :
Final output is : 15 7 5 4
15 7 5 3 9 6 2 4 32