Timer is Running

Sort by Set Bit Count
##### Submissions: 3069   Accuracy: 31.12%   Difficulty: Easy   Marks: 2

Given an array of integers, sort the array (in descending order) according to count of set bits in binary representation 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.

```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  - 0110
5  - 0101
6  - 0110
1  - 0001
2  - 0010
4  - 0100
hence the non-increasing sorted order is
{3, 5, 6}, {1, 2, 4}

Expected Time Complexity: O(N.log(N))
Expected Auxiliary Space: O(1)

```

Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated array elements.

Output:
Print each sorted array in a seperate line. For each array its numbers should be seperated by space.

Constraints:
1 ≤ T ≤ 30
0 ≤ N ≤ 105
1 ≤ A[i] ≤ 106

Example:

Input:

2
3
3 1 5
4
5 16 6 15

Output:

3 5 1
15 5 6 16

#### ** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Nikhil Chakravartula.
Author: kartik

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.