# Sort an array according to count of set bits

Given an array of positive integers, sort the array in decreasing order of count of set bits in binary representations of array elements.
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. For example, if input array is {3, 5}, then output array should also be {3, 5}. Note that both 3 and 5 have same number set bits.

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

Method 1: Simple

1. Create an auxiliary array and store the set-bit counts of all integers in the aux array
2. Simultaneously sort both arrays according to the non-increasing order of auxiliary array. (Note that we need to use a stable sort algorithm)

Before sort:
int arr[] = {1, 2, 3, 4, 5, 6};
int aux[] = {1, 1, 2, 1, 2, 2}

After sort:
arr = {3, 5, 6, 1, 2, 4}
aux = {2, 2, 2, 1, 1, 1}

Implementation:

## C++

 `// C++ program to implement simple approach to sort ` `// an array according to count of set bits. ` `#include ` ` `  `using` `namespace` `std; ` ` `  `// a utility function that returns total set bits ` `// count in an integer ` `int` `countBits(``int` `a) ` `{ ` `    ``int` `count = 0; ` `    ``while` `(a) ` `    ``{ ` `        ``if` `(a & 1 ) ` `            ``count+= 1; ` `        ``a = a>>1; ` `    ``} ` `    ``return` `count; ` `} ` ` `  `// Function to simultaneously sort both arrays ` `// using insertion sort  ` `// ( http://quiz.geeksforgeeks.org/insertion-sort/ ) ` `void` `insertionSort(``int` `arr[],``int` `aux[], ``int` `n) ` `{ ` `    ``for` `(``int` `i = 1; i < n; i++) ` `    ``{ ` `        ``// use 2 keys because we need to sort both ` `        ``// arrays simultaneously ` `        ``int` `key1 = aux[i]; ` `        ``int` `key2 = arr[i]; ` `        ``int` `j = i-1; ` ` `  `        ``/* Move elements of arr[0..i-1] and aux[0..i-1], ` `           ``such that elements of aux[0..i-1] are ` `           ``greater than key1, to one position ahead ` `           ``of their current position */` `        ``while` `(j >= 0 && aux[j] < key1) ` `        ``{ ` `            ``aux[j+1] = aux[j]; ` `            ``arr[j+1] = arr[j]; ` `            ``j = j-1; ` `        ``} ` `        ``aux[j+1] = key1; ` `        ``arr[j+1] = key2; ` `    ``} ` `} ` ` `  `// Function to sort according to bit count using ` `// an auxiliary array ` `void` `sortBySetBitCount(``int` `arr[],``int` `n) ` `{ ` `    ``// Create an array and store count of ` `    ``// set bits in it. ` `    ``int` `aux[n]; ` `    ``for` `(``int` `i=0; i

## Java

 `// Java program to implement  ` `// simple approach to sort ` `// an array according to  ` `// count of set bits. ` `import` `java.io.*; ` ` `  `class` `GFG  ` `{ ` ` `  `// a utility function that  ` `// returns total set bits ` `// count in an integer ` `static` `int` `countBits(``int` `a) ` `{ ` `    ``int` `count = ``0``; ` `    ``while` `(a > ``0``) ` `    ``{ ` `        ``if` `((a & ``1``) > ``0``) ` `            ``count+= ``1``; ` `        ``a = a >> ``1``; ` `    ``} ` `    ``return` `count; ` `} ` ` `  `// Function to simultaneously  ` `// sort both arrays using  ` `// insertion sort  ` `// (http://quiz.geeksforgeeks.org/insertion-sort/ ) ` `static` `void` `insertionSort(``int` `arr[], ` `                          ``int` `aux[], ``int` `n) ` `{ ` `    ``for` `(``int` `i = ``1``; i < n; i++) ` `    ``{ ` `        ``// use 2 keys because we  ` `        ``// need to sort both ` `        ``// arrays simultaneously ` `        ``int` `key1 = aux[i]; ` `        ``int` `key2 = arr[i]; ` `        ``int` `j = i - ``1``; ` ` `  `        ``/* Move elements of arr[0..i-1]  ` `        ``and aux[0..i-1], such that  ` `        ``elements of aux[0..i-1] are ` `        ``greater than key1, to one  ` `        ``position ahead of their current ` `        ``position */` `        ``while` `(j >= ``0` `&& aux[j] < key1) ` `        ``{ ` `            ``aux[j + ``1``] = aux[j]; ` `            ``arr[j + ``1``] = arr[j]; ` `            ``j = j - ``1``; ` `        ``} ` `        ``aux[j + ``1``] = key1; ` `        ``arr[j + ``1``] = key2; ` `    ``} ` `} ` ` `  `// Function to sort according ` `// to bit count using an  ` `// auxiliary array ` `static` `void` `sortBySetBitCount(``int` `arr[], ` `                              ``int` `n) ` `{ ` `    ``// Create an array and  ` `    ``// store count of ` `    ``// set bits in it. ` `    ``int` `aux[] = ``new` `int``[n]; ` `    ``for` `(``int` `i = ``0``; i < n; i++) ` `        ``aux[i] = countBits(arr[i]); ` ` `  `    ``// Sort arr[] according  ` `    ``// to values in aux[] ` `    ``insertionSort(arr, aux, n); ` `} ` ` `  `// Utility function ` `// to print an array ` `static` `void` `printArr(``int` `arr[], ``int` `n) ` `{ ` `    ``for` `(``int` `i = ``0``; i < n; i++) ` `        ``System.out.print(arr[i] + ``" "``); ` `} ` ` `  `// Driver Code ` `public` `static` `void` `main (String[] args)  ` `{ ` `    ``int` `arr[] = {``1``, ``2``, ``3``, ``4``, ``5``, ``6``}; ` `    ``int` `n = arr.length; ` `    ``sortBySetBitCount(arr, n); ` `    ``printArr(arr, n); ` `} ` `} ` ` `  `// This code is contributed by anuj_67. `

## Python3

 `# Python 3 program to implement simple approach to sort ` `# an array according to count of set bits. ` ` `  `# a utility function that returns total set bits ` `# count in an integer ` `def` `countBits(a): ` `    ``count ``=` `0` `    ``while` `(a): ` `        ``if` `(a & ``1``): ` `            ``count``+``=` `1` `        ``a ``=` `a>>``1` ` `  `    ``return` `count ` ` `  `# Function to simultaneously sort both arrays ` `# using insertion sort  ` `# ( http:#quiz.geeksforgeeks.org/insertion-sort/ ) ` `def` `insertionSort(arr,aux, n): ` `    ``for` `i ``in` `range``(``1``,n,``1``): ` `        ``# use 2 keys because we need to sort both ` `        ``# arrays simultaneously ` `        ``key1 ``=` `aux[i] ` `        ``key2 ``=` `arr[i] ` `        ``j ``=` `i``-``1` ` `  `        ``# Move elements of arr[0..i-1] and aux[0..i-1], ` `        ``#  such that elements of aux[0..i-1] are ` `        ``# greater than key1, to one position ahead ` `        ``#  of their current position */ ` `        ``while` `(j >``=` `0` `and` `aux[j] < key1): ` `            ``aux[j``+``1``] ``=` `aux[j] ` `            ``arr[j``+``1``] ``=` `arr[j] ` `            ``j ``=` `j``-``1` ` `  `        ``aux[j``+``1``] ``=` `key1 ` `        ``arr[j``+``1``] ``=` `key2 ` ` `  `# Function to sort according to bit count using ` `# an auxiliary array ` `def` `sortBySetBitCount(arr, n): ` `    ``# Create an array and store count of ` `    ``# set bits in it. ` `    ``aux ``=` `[``0` `for` `i ``in` `range``(n)] ` `    ``for` `i ``in` `range``(``0``,n,``1``): ` `        ``aux[i] ``=` `countBits(arr[i]) ` ` `  `    ``# Sort arr[] according to values in aux[] ` `    ``insertionSort(arr, aux, n) ` ` `  `# Utility function to print an array ` `def` `printArr(arr, n): ` `    ``for` `i ``in` `range``(``0``,n,``1``): ` `        ``print``(arr[i],end ``=` `" "``) ` ` `  `# Driver Code ` `if` `__name__ ``=``=``'__main__'``: ` `    ``arr ``=` `[``1``, ``2``, ``3``, ``4``, ``5``, ``6``] ` `    ``n ``=` `len``(arr) ` `    ``sortBySetBitCount(arr, n) ` `    ``printArr(arr, n) ` ` `  `# This code is contributed by ` `# Surendra_Gangwar `

## C#

 `// C# program to implement  ` `// simple approach to sort  ` `// an array according to  ` `// count of set bits.  ` ` `  `using` `System; ` ` `  `public` `class` `GFG{ ` `     `  `// a utility function that  ` `// returns total set bits  ` `// count in an integer  ` `static` `int` `countBits(``int` `a)  ` `{  ` `    ``int` `count = 0;  ` `    ``while` `(a > 0)  ` `    ``{  ` `        ``if` `((a & 1) > 0)  ` `            ``count+= 1;  ` `        ``a = a >> 1;  ` `    ``}  ` `    ``return` `count;  ` `}  ` ` `  `// Function to simultaneously  ` `// sort both arrays using  ` `// insertion sort  ` `// (http://quiz.geeksforgeeks.org/insertion-sort/ ) ` `// Function to simultaneously  ` `// sort both arrays using  ` `// insertion sort  ` `// (http://quiz.geeksforgeeks.org/insertion-sort/ )  ` `static` `void` `insertionSort(``int` `[]arr,  ` `                        ``int` `[]aux, ``int` `n)  ` `{  ` `    ``for` `(``int` `i = 1; i < n; i++)  ` `    ``{  ` `        ``// use 2 keys because we  ` `        ``// need to sort both  ` `        ``// arrays simultaneously  ` `        ``int` `key1 = aux[i];  ` `        ``int` `key2 = arr[i];  ` `        ``int` `j = i - 1;  ` ` `  `        ``/* Move elements of arr[0..i-1]  ` `        ``and aux[0..i-1], such that  ` `        ``elements of aux[0..i-1] are  ` `        ``greater than key1, to one  ` `        ``position ahead of their current  ` `        ``position */` `        ``while` `(j >= 0 && aux[j] < key1)  ` `        ``{  ` `            ``aux[j + 1] = aux[j];  ` `            ``arr[j + 1] = arr[j];  ` `            ``j = j - 1;  ` `        ``}  ` `        ``aux[j + 1] = key1;  ` `        ``arr[j + 1] = key2;  ` `    ``}  ` `}  ` ` `  `// Function to sort according  ` `// to bit count using an  ` `// auxiliary array  ` `static` `void` `sortBySetBitCount(``int` `[]arr,  ` `                            ``int` `n)  ` `{  ` `    ``// Create an array and  ` `    ``// store count of  ` `    ``// set bits in it.  ` `    ``int` `[]aux = ``new` `int``[n];  ` `    ``for` `(``int` `i = 0; i < n; i++)  ` `        ``aux[i] = countBits(arr[i]);  ` ` `  `    ``// Sort arr[] according  ` `    ``// to values in aux[]  ` `    ``insertionSort(arr, aux, n);  ` `}  ` ` `  `// Utility function  ` `// to print an array  ` `static` `void` `printArr(``int` `[]arr, ``int` `n)  ` `{  ` `    ``for` `(``int` `i = 0; i < n; i++)  ` `        ``Console.Write(arr[i] + ``" "``);  ` `}  ` ` `  `// Driver Code  ` `    ``static` `public` `void` `Main (){ ` `        ``int` `[]arr = {1, 2, 3, 4, 5, 6};  ` `    ``int` `n = arr.Length;  ` `    ``sortBySetBitCount(arr, n);  ` `    ``printArr(arr, n);  ` `    ``} ` `} `

Output:

`3 5 6 1 2 4 `

Auxiliary Space: O(n)
Time complexity: O(n2)

Not e: Time complexity can be improved to O(nLogn) by using a stable O(nlogn) sorting algorithm.

Method 2 : Using std::sort()
Using custom comparator of std::sort to sort the array according to set-bit count

## C++

 `// C++ program to sort an array according to ` `// count of set bits using std::sort() ` `#include ` ` `  `using` `namespace` `std; ` ` `  `// a utility function that returns total set bits ` `// count in an integer ` `int` `countBits(``int` `a) ` `{ ` `    ``int` `count = 0; ` `    ``while` `(a) ` `    ``{ ` `        ``if` `(a & 1 ) ` `            ``count+= 1; ` `        ``a = a>>1; ` `    ``} ` `    ``return` `count; ` `} ` ` `  `// custom comparator of std::sort ` `int` `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 according to bit count using ` `// std::sort ` `void` `sortBySetBitCount(``int` `arr[], ``int` `n) ` `{ ` `    ``stable_sort(arr, arr+n, cmp); ` `} ` ` `  `// Utility function to print an array ` `void` `printArr(``int` `arr[], ``int` `n) ` `{ ` `    ``for` `(``int` `i=0; i

Output:

`3 5 6 1 2 4 `

Auxiliary Space : O(1)
Time complexity : O(n log n)

Method 3 : Counting Sort based

This problem can be solved in O(n) time. The idea is similar to counting sort.

Note: There can be minimum 1 set-bit and only a maximum of 31set-bits in any integer.

Steps (assuming that an integer takes 32 bits):

1. Create a vector “count” of size 32. Each cell of count i.e., count[i] is another vector that stores all the elements whose set-bit-count is i
2. Traverse the array and do following for each element:
1. Count the number set-bits of this element. Let it be ‘setbitcount’
2. count[setbitcount].push_back(element)
3. Traverse ‘count’ in reverse fashion(as we need to sort in non-increasing order) and modify the array. ## C++

 `// C++ program to sort an array according to ` `// count of set bits using std::sort() ` `#include ` `using` `namespace` `std; ` ` `  `// a utility function that returns total set bits ` `// count in an integer ` `int` `countBits(``int` `a) ` `{ ` `    ``int` `count = 0; ` `    ``while` `(a) ` `    ``{ ` `        ``if` `(a & 1 ) ` `            ``count+= 1; ` `        ``a = a>>1; ` `    ``} ` `    ``return` `count; ` `} ` ` `  `// Function to sort according to bit count ` `// This function assumes that there are 32 ` `// bits in an integer. ` `void` `sortBySetBitCount(``int` `arr[],``int` `n) ` `{ ` `    ``vector > count(32); ` `    ``int` `setbitcount = 0; ` `    ``for` `(``int` `i=0; i=0; i--) ` `    ``{ ` `        ``vector<``int``> v1 = count[i]; ` `        ``for` `(``int` `i=0; i

Output:

`3 5 6 1 2 4 `

## tags:

Arrays Sorting Deutsche Bank Arrays Sorting