VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-array-according-count-set-bits/

⇱ Sort by Set Bit Count - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort by Set Bit Count

Last Updated : 23 Apr, 2026

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}.

[Naive Approach] - Using Inbuilt Sort Function - O(n * log n) Time and O(1) Space

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] :

  • Compute set bits for each element.
    5 (binary : 101) = 2 bits, 4 (binary : 100) = 1 bit, 7 (binary : 111) = 3 bits and 15 (binary : 1111) = 4 bits
  • Group elements based on set bits (preserving original order).
    4 bits = [15], 3 bits = [7], 2 bits = [5], 1 bit = [4]
  • Arrange groups in descending order of set bits.
    [15] + [7] + [5] + [4]

Final output: 15 7 5 4


Output
15 7 5 3 9 6 2 4 32 

[Expected Approach] - Using Counting Sort - O(n) Time and O(n) Space

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] :

  • Compute set bits and place into buckets:
    5 (binary : 101) = 2 bits, count[2] = [5]
    4 (binary : 100) = 1 bit, count[1] = [4]
    7 (binary : 111) = 3 bits, count[3] = [7]
    15 (binary : 1111) = 4 bits, count[4] = [15]
  • Buckets after filling:
    count[4] = [15], count[3] = [7], count[2] = [5], count[1] = [4], others = []
  • Build result (from highest bit count to lowest):
    For i=31 = []
    For i=30 = []
    ...
    For i=4 = [15]
    For i=3 = [15, 7]
    For i=2 = [15, 7, 5]
    For i=1 = [15, 7, 5, 4]
    For i=0 = no change

Final output is : 15 7 5 4


Output
15 7 5 3 9 6 2 4 32 
Comment
Article Tags: