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}

**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 ≤ 1000

0 ≤ N ≤ 100000

1 ≤ A[i] ≤ 1000000

**Example:**

**Input:**

2

3

3 1 5

4

5 16 6 15

**Output:**

3 5 1

15 5 6 16

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.

msriramvarma01 | 25 |

AbhilashKumar2 | 24 |

monusinghal | 24 |

tripurari_IT | 24 |

Abreez Das | 23 |

ARUN_PUNDIR | 609 |

manishgupta8497 | 607 |

KhyatiSoneji | 501 |

Abhimanyu_kumar | 487 |

vvggfggcg | 453 |

blackshadows | 5333 |

Ibrahim Nash | 5221 |

akhayrutdinov | 5111 |

mb1973 | 4929 |

Quandray | 4567 |

Login to report an issue on this page.