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.

saiujwal13083 | 489 |

sudeep235poojary | 302 |

VithalNakod | 272 |

AshutoshPal1 | 254 |

go__karuna | 253 |

Soseph_Jtalin | 792 |

AshutoshPal1 | 722 |

architjindal__ | 648 |

go__karuna | 577 |

ArbazGrewal | 527 |

blackshadows | 5362 |

Ibrahim Nash | 5242 |

akhayrutdinov | 5111 |

mb1973 | 4931 |

Quandray | 4598 |

Login to report an issue on this page.