Sort an array according to count of set bits (original) (raw)

Last Updated : 10 Mar, 2025

Try it on GfG Practice redirect icon

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

[Naive Approach] - Using Insertion Sort - O(n ^ 2) Time and O(n) Space

The idea is to store the set-bit counts of all the integers in the auxiliary array and simultaneously sort both arrays according to the non-increasing order of auxiliary array.

C++ `

#include <bits/stdc++.h> using namespace std;

// Function to simultaneously sort both // arrays using insertion sort void insertionSort(vector &arr, vector &bitCnt) { int n = arr.size();

for (int i = 1; i < n; i++) {
    int key1 = bitCnt[i];
    int key2 = arr[i];
    int j = i - 1;

    while (j >= 0 && bitCnt[j] < key1) {
        bitCnt[j + 1] = bitCnt[j];
        arr[j + 1] = arr[j];
        j = j - 1;
    }
    bitCnt[j + 1] = key1;
    arr[j + 1] = key2;
}

}

// Function to count set bits in an integer int countBits(int a) { int count = 0; while (a) { if (a % 2 != 0) count += 1; a = a / 2; } return count; }

// Function to sort an array according to bit count void sortBySetBitCount(vector& arr) { int n = arr.size();

// Create an array and store 
// count of set bits in it.
vector<int> bitCnt(n);
for (int i = 0; i < n; i++)
    bitCnt[i] = countBits(arr[i]);

// sort the array 
insertionSort(arr, bitCnt);

}

int main() { vector arr = { 5, 2, 3, 9, 4, 6, 7, 15, 32 }; sortBySetBitCount(arr); for (int i = 0; i < arr.size(); i++) cout << arr[i] << " "; return 0; }

Java

// Function to simultaneously sort both // arrays using insertion sort import java.util.*;

class GfG {

// Function to simultaneously sort both 
// arrays using insertion sort
static void insertionSort(int[] arr, int[] bitCnt) {
    int n = arr.length;
    
    for (int i = 1; i < n; i++) {
        int key1 = bitCnt[i];
        int key2 = arr[i];
        int j = i - 1;
        
        while (j >= 0 && bitCnt[j] < key1) {
            bitCnt[j + 1] = bitCnt[j];
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        bitCnt[j + 1] = key1;
        arr[j + 1] = key2;
    }
}

// Function to count set bits in an integer
static int countBits(int a) {
    int count = 0;
    while (a != 0) {
        if (a % 2 != 0)
            count += 1;
        a = a / 2;
    }
    return count;
}

// Function to sort an array according to bit count
static void sortBySetBitCount(int[] arr) {
    int n = arr.length;
    
    // Create an array and store 
    // count of set bits in it.
    int[] bitCnt = new int[n];
    for (int i = 0; i < n; i++)
        bitCnt[i] = countBits(arr[i]);
    
    // sort the array 
    insertionSort(arr, bitCnt);
}

public static void main(String[] args) {
    int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
    sortBySetBitCount(arr);
    for (int i = 0; i < arr.length; i++)
        System.out.print(arr[i] + " ");
}

}

Python

Function to simultaneously sort both

arrays using insertion sort

def insertionSort(arr, bitCnt): n = len(arr)

for i in range(1, n):
    key1 = bitCnt[i]
    key2 = arr[i]
    j = i - 1
    
    while j >= 0 and bitCnt[j] < key1:
        bitCnt[j + 1] = bitCnt[j]
        arr[j + 1] = arr[j]
        j = j - 1
    bitCnt[j + 1] = key1
    arr[j + 1] = key2

Function to count set bits in an integer

def countBits(a): count = 0 while a: if a % 2 != 0: count += 1 a = a // 2 return count

Function to sort an array according to bit count

def sortBySetBitCount(arr): n = len(arr)

# Create an array and store 
# count of set bits in it.
bitCnt = [0] * n
for i in range(n):
    bitCnt[i] = countBits(arr[i])

# sort the array 
insertionSort(arr, bitCnt)

if name == "main": arr = [5, 2, 3, 9, 4, 6, 7, 15, 32] sortBySetBitCount(arr) for i in range(len(arr)): print(arr[i], end=" ")

C#

// Function to simultaneously sort both // arrays using insertion sort using System; using System.Collections.Generic;

class GfG {

// Function to simultaneously sort both 
// arrays using insertion sort
static void insertionSort(int[] arr, int[] bitCnt) {
    int n = arr.Length;
    
    for (int i = 1; i < n; i++) {
        int key1 = bitCnt[i];
        int key2 = arr[i];
        int j = i - 1;
        
        while (j >= 0 && bitCnt[j] < key1) {
            bitCnt[j + 1] = bitCnt[j];
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        bitCnt[j + 1] = key1;
        arr[j + 1] = key2;
    }
}

// Function to count set bits in an integer
static int countBits(int a) {
    int count = 0;
    while (a != 0) {
        if (a % 2 != 0)
            count += 1;
        a = a / 2;
    }
    return count;
}

// Function to sort an array according to bit count
static void sortBySetBitCount(int[] arr) {
    int n = arr.Length;
    
    // Create an array and store 
    // count of set bits in it.
    int[] bitCnt = new int[n];
    for (int i = 0; i < n; i++)
        bitCnt[i] = countBits(arr[i]);
    
    // sort the array 
    insertionSort(arr, bitCnt);
}

static void Main() {
    int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
    sortBySetBitCount(arr);
    for (int i = 0; i < arr.Length; i++)
        Console.Write(arr[i] + " ");
}

}

JavaScript

// Function to simultaneously sort both // arrays using insertion sort function insertionSort(arr, bitCnt) { let n = arr.length;

for (let i = 1; i < n; i++) {
    let key1 = bitCnt[i];
    let key2 = arr[i];
    let j = i - 1;
    
    while (j >= 0 && bitCnt[j] < key1) {
        bitCnt[j + 1] = bitCnt[j];
        arr[j + 1] = arr[j];
        j = j - 1;
    }
    bitCnt[j + 1] = key1;
    arr[j + 1] = key2;
}

}

// Function to count set bits in an integer function countBits(a) { let count = 0; while (a) { if (a % 2 !== 0) count += 1; a = Math.floor(a / 2); } return count; }

// Function to sort an array according to bit count function sortBySetBitCount(arr) { let n = arr.length;

// Create an array and store 
// count of set bits in it.
let bitCnt = new Array(n).fill(0);
for (let i = 0; i < n; i++)
    bitCnt[i] = countBits(arr[i]);

// sort the array 
insertionSort(arr, bitCnt);

}

let arr = [5, 2, 3, 9, 4, 6, 7, 15, 32]; sortBySetBitCount(arr); for (let i = 0; i < arr.length; i++) process.stdout.write(arr[i] + " ");

`

Output

15 7 5 3 9 6 2 4 32

[Better 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.

C++ `

#include <bits/stdc++.h> using namespace std;

// Function to count set bits in an integer int countBits(int a) { int count = 0; while (a) { if (a % 2 != 0) count += 1; a = a / 2; } return count; }

// custom comparator of std::sort bool 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;

}

// Function to sort an array according to bit count void sortBySetBitCount(vector& arr) { stable_sort(arr.begin(), arr.end(), cmp); }

int main() { vector arr = { 5, 2, 3, 9, 4, 6, 7, 15, 32 }; sortBySetBitCount(arr); for (int i = 0; i < arr.size(); i++) cout << arr[i] << " "; return 0; }

Java

// Function to count set bits in an integer import java.util.*;

class GfG {

// Function to count set bits in an integer
static int countBits(int a) {
    int count = 0;
    while (a != 0) {
        if (a % 2 != 0)
            count += 1;
        a = a / 2;
    }
    return count;
}

// Function to sort an array according to bit count
// using stable sort
static int[] sortBySetBitCount(int[] arr) {
    int n = arr.length;
    Integer[] arrObj = new Integer[n];
    for (int i = 0; i < n; i++) {
        arrObj[i] = arr[i];
    }
    Arrays.sort(arrObj, new Comparator<Integer>() {
        public int compare(Integer a, Integer b) {
            int c1 = countBits(a);
            int c2 = countBits(b);
            if(c1 == c2)
                return 0;
            return c1 < c2 ? 1 : -1;
        }
    });
    int[] ans = new int[n];
    for (int i = 0; i < n; i++) {
        ans[i] = arrObj[i];
    }
    return ans;
}

public static void main(String[] args) {
    int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
    int[] ans = sortBySetBitCount(arr);
    for (int i = 0; i < ans.length; i++)
        System.out.print(ans[i] + " ");
}

}

Python

Function to count set bits in an integer

def countBits(a): count = 0 while a: if a % 2 != 0: count += 1 a //= 2 return count

Function to sort an array according to bit count

using stable sort

def sortBySetBitCount(arr): arr.sort(key=lambda x: -countBits(x)) return arr

if name == "main": arr = [5, 2, 3, 9, 4, 6, 7, 15, 32] sortBySetBitCount(arr) for i in range(len(arr)): print(arr[i], end=" ")

C#

// Function to count set bits in an integer using System; using System.Linq;

class GfG {

// Function to count set bits in an integer
static int countBits(int a) {
    int count = 0;
    while (a != 0) {
        if (a % 2 != 0)
            count += 1;
        a = a / 2;
    }
    return count;
}

// Function to sort an array according to bit count
// using stable sort
static int[] sortBySetBitCount(int[] arr) {
    int n = arr.Length;
    var sorted = arr.Select((x, i) => new { Value = x, Index = i })
                    .OrderByDescending(item => countBits(item.Value))
                    .ThenBy(item => item.Index)
                    .Select(item => item.Value)
                    .ToArray();
    return sorted;
}

static void Main() {
    int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
    int[] ans = sortBySetBitCount(arr);
    for (int i = 0; i < ans.Length; i++)
        Console.Write(ans[i] + " ");
}

}

JavaScript

// Function to count set bits in an integer function countBits(a) { let count = 0; while (a) { if (a % 2 !== 0) count += 1; a = Math.floor(a / 2); } return count; }

// Function to sort an array according to bit count // using stable sort function sortBySetBitCount(arr) { arr.sort((a, b) => { let c1 = countBits(a); let c2 = countBits(b); if (c1 === c2) return 0; return c1 < c2 ? 1 : -1; }); return arr; }

let arr = [5, 2, 3, 9, 4, 6, 7, 15, 32]; sortBySetBitCount(arr); for (let i = 0; i < arr.length; i++) process.stdout.write(arr[i] + " ");

`

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.

Capture

C++ `

#include <bits/stdc++.h> using namespace std;

// Function to count set bits in an integer int countBits(int a) { int count = 0; while (a) { if (a % 2 != 0) count += 1; a = a / 2; } return count; }

// Function to sort an array according to bit count void sortBySetBitCount(vector& arr) { int n = arr.size();

// Create a 2d array to map array elements
// to their corresponding set bit count
vector<vector<int>> count(32);

// insert elements in the 2d array
for (int i=0; i<n; i++) {
    int setBit = countBits(arr[i]);
    count[setBit].push_back(arr[i]);
}

// to track the index of sorted array
int j = 0;

// Traverse through all bit counts
for (int i = 31; i >= 0; i--) {

    // Traverse through all elements 
    // of current bit count
    for(int k = 0; k < count[i].size(); k++) {
        arr[j++] = count[i][k];
    }
}

}

int main() { vector arr = { 5, 2, 3, 9, 4, 6, 7, 15, 32 }; sortBySetBitCount(arr); for (int i = 0; i < arr.size(); i++) cout << arr[i] << " "; return 0; }

Java

// Function to count set bits in an integer import java.util.*;

class GfG {

// Function to count set bits in an integer
static int countBits(int a) {
    int count = 0;
    while (a != 0) {
        if (a % 2 != 0)
            count += 1;
        a = a / 2;
    }
    return count;
}

// Function to sort an array according to bit count
static void sortBySetBitCount(int[] arr) {
    int n = arr.length;
    
    // Create a 2d array to map array elements
    // to their corresponding set bit count
    ArrayList<ArrayList<Integer>> count = new ArrayList<>();
    for (int i = 0; i < 32; i++) {
        count.add(new ArrayList<>());
    }
    
    // insert elements in the 2d array
    for (int i = 0; i < n; i++) {
        int setBit = countBits(arr[i]);
        count.get(setBit).add(arr[i]);
    }
    
    // to track the index of sorted array
    int j = 0;
    
    // Traverse through all bit counts
    for (int i = 31; i >= 0; i--) {
        // Traverse through all elements 
        // of current bit count
        ArrayList<Integer> curr = count.get(i);
        for (int k = 0; k < curr.size(); k++) {
            arr[j++] = curr.get(k);
        }
    }
}

public static void main(String[] args) {
    int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
    sortBySetBitCount(arr);
    for (int i = 0; i < arr.length; i++)
        System.out.print(arr[i] + " ");
}

}

Python

Function to count set bits in an integer

def countBits(a): count = 0 while a: if a % 2 != 0: count += 1 a = a // 2 return count

Function to sort an array according to bit count

def sortBySetBitCount(arr): n = len(arr)

# Create a 2d array to map array elements
# to their corresponding set bit count
count = [[] for _ in range(32)]

# insert elements in the 2d array
for i in range(n):
    setBit = countBits(arr[i])
    count[setBit].append(arr[i])

# to track the index of sorted array
j = 0

# Traverse through all bit counts
for i in range(31, -1, -1):
    # Traverse through all elements 
    # of current bit count
    for k in range(len(count[i])):
        arr[j] = count[i][k]
        j += 1

Driver Code

if name == "main": arr = [5, 2, 3, 9, 4, 6, 7, 15, 32] sortBySetBitCount(arr) for i in range(len(arr)): print(arr[i], end=" ")

C#

// Function to count set bits in an integer using System; using System.Collections.Generic;

class GfG {

// Function to count set bits in an integer
static int countBits(int a) {
    int count = 0;
    while (a != 0) {
        if (a % 2 != 0)
            count += 1;
        a = a / 2;
    }
    return count;
}

// Function to sort an array according to bit count
static void sortBySetBitCount(int[] arr) {
    int n = arr.Length;
    
    // Create a 2d array to map array elements
    // to their corresponding set bit count
    List<List<int>> count = new List<List<int>>();
    for (int i = 0; i < 32; i++) {
        count.Add(new List<int>());
    }
    
    // insert elements in the 2d array
    for (int i = 0; i < n; i++) {
        int setBit = countBits(arr[i]);
        count[setBit].Add(arr[i]);
    }
    
    // to track the index of sorted array
    int j = 0;
    
    // Traverse through all bit counts
    for (int i = 31; i >= 0; i--) {
        // Traverse through all elements 
        // of current bit count
        for (int k = 0; k < count[i].Count; k++) {
            arr[j++] = count[i][k];
        }
    }
}

static void Main() {
    int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
    sortBySetBitCount(arr);
    for (int i = 0; i < arr.Length; i++)
        Console.Write(arr[i] + " ");
}

}

JavaScript

// Function to count set bits in an integer function countBits(a) { let count = 0; while (a) { if (a % 2 !== 0) count += 1; a = Math.floor(a / 2); } return count; }

// Function to sort an array according to bit count function sortBySetBitCount(arr) { let n = arr.length;

// Create a 2d array to map array elements
// to their corresponding set bit count
let count = [];
for (let i = 0; i < 32; i++) {
    count.push([]);
}

// insert elements in the 2d array
for (let i = 0; i < n; i++) {
    let setBit = countBits(arr[i]);
    count[setBit].push(arr[i]);
}

// to track the index of sorted array
let j = 0;

// Traverse through all bit counts
for (let i = 31; i >= 0; i--) {
    // Traverse through all elements 
    // of current bit count
    for (let k = 0; k < count[i].length; k++) {
        arr[j++] = count[i][k];
    }
}

}

let arr = [5, 2, 3, 9, 4, 6, 7, 15, 32]; sortBySetBitCount(arr); for (let i = 0; i < arr.length; i++) process.stdout.write(arr[i] + " ");

`

Output

15 7 5 3 9 6 2 4 32

[Alternate Approach] - Using Multimap - O(n * log n) Time and O(n) Space

The idea is store the elements corresponding to negative (to ensure elements are sorted in descending order) of their count of set-bits in a multimap.

#include <bits/stdc++.h> using namespace std;

// Function to count set bits in an integer int countBits(int a) { int count = 0; while (a) { if (a % 2 != 0) count += 1; a = a / 2; } return count; }

// Function to sort an array according to bit count void sortBySetBitCount(vector& arr) { int n = arr.size();

// to map the elements to their
// corresponding set bit count
multimap<int, int> count;

// Iterate over all values and 
// insert into multimap
for( int i = 0 ; i < n ; i++ ) {
    count.insert({(-1) * countBits(arr[i]), arr[i]});
}

int j = 0;

// Iterate over all values and
// insert into the array
for(auto i: count) {
    arr[j++] = i.second;
}

}

int main() { vector arr = { 5, 2, 3, 9, 4, 6, 7, 15, 32 }; sortBySetBitCount(arr); for (int i = 0; i < arr.size(); i++) cout << arr[i] << " "; return 0; }

Java

// Function to count set bits in an integer import java.util.*;

class Pair { int val; int idx;

Pair(int val, int idx) {
    this.val = val;
    this.idx = idx;
}

}

class GfG {

// Function to count set bits in an integer
static int countBits(int a) {
    int count = 0;
    while (a != 0) {
        if (a % 2 != 0)
            count += 1;
        a = a / 2;
    }
    return count;
}

// Function to sort an array according to bit count
static int[] sortBySetBitCount(int[] arr) {
    int n = arr.length;
    Pair[] pairs = new Pair[n];
    for (int i = 0; i < n; i++) {
        pairs[i] = new Pair(arr[i], i);
    }
    
    Arrays.sort(pairs, new Comparator<Pair>() {
        public int compare(Pair p1, Pair p2) {
            int c1 = countBits(p1.val);
            int c2 = countBits(p2.val);
            if (c1 == c2)
                return Integer.compare(p1.idx, p2.idx);
            return Integer.compare(c2, c1);
        }
    });
    
    int[] ans = new int[n];
    for (int i = 0; i < n; i++) {
        ans[i] = pairs[i].val;
    }
    return ans;
}

public static void main(String[] args) {
    int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
    int[] ans = sortBySetBitCount(arr);
    for (int i = 0; i < ans.length; i++)
        System.out.print(ans[i] + " ");
}

}

Python

Function to count set bits in an integer

def countBits(a): count = 0 while a: if a % 2 != 0: count += 1 a //= 2 return count

Function to sort an array according to bit count

def sortBySetBitCount(arr): n = len(arr)

# Create an array of (index, value) pairs
paired = list(enumerate(arr))

# Stable sort: first by descending countBits, then by original index
paired.sort(key=lambda x: (-countBits(x[1]), x[0]))

ans = [x[1] for x in paired]
return ans

if name == "main": arr = [5, 2, 3, 9, 4, 6, 7, 15, 32] ans = sortBySetBitCount(arr) for i in range(len(ans)): print(ans[i], end=" ")

C#

// Function to count set bits in an integer using System; using System.Linq; using System.Collections.Generic;

class GfG {

// Function to count set bits in an integer
static int countBits(int a) {
    int count = 0;
    while (a != 0) {
        if (a % 2 != 0)
            count += 1;
        a = a / 2;
    }
    return count;
}

// Function to sort an array according to bit count
static int[] sortBySetBitCount(int[] arr) {
    int n = arr.Length;
    var paired = arr.Select((val, idx) => new { val, idx });
    var sorted = paired.OrderByDescending(x => countBits(x.val))
                       .ThenBy(x => x.idx)
                       .Select(x => x.val)
                       .ToArray();
    return sorted;
}

static void Main() {
    int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
    int[] ans = sortBySetBitCount(arr);
    for (int i = 0; i < ans.Length; i++)
        Console.Write(ans[i] + " ");
}

}

JavaScript

// Function to count set bits in an integer function countBits(a) { let count = 0; while (a) { if (a % 2 !== 0) count += 1; a = Math.floor(a / 2); } return count; }

// Function to sort an array according to bit count function sortBySetBitCount(arr) { let n = arr.length;

// Create an array of pairs [index, value]
let paired = arr.map((val, idx) => [idx, val]);

// Stable sort: first by descending countBits, then by original index
paired.sort((a, b) => {
    let c1 = countBits(a[1]);
    let c2 = countBits(b[1]);
    if (c1 === c2)
        return a[0] - b[0];
    return c2 - c1;
});

let ans = paired.map(x => x[1]);
return ans;

}

let arr = [5, 2, 3, 9, 4, 6, 7, 15, 32]; let ans = sortBySetBitCount(arr); for (let i = 0; i < ans.length; i++) process.stdout.write(ans[i] + " ");

`

Output

15 7 5 3 9 6 2 4 32