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.

codersanjeev | 66 |

snow_den_ | 60 |

BoggavarapuRamSaranSaiSrinivasGupta | 60 |

rajupraaa1234 | 53 |

SUZAKU | 49 |

mr_kksparrow | 433 |

manvirag982 | 258 |

snow_den_ | 232 |

arpit_anshuman | 228 |

SoumyaKaushik | 205 |

blackshadows | 5331 |

Ibrahim Nash | 5219 |

akhayrutdinov | 5111 |

mb1973 | 4929 |

Quandray | 4567 |

Login to report an issue on this page.