Timer is Running

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 ≤ 10^{5}

1 ≤ A[i] ≤ 10^{6}

**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 | 155 |

vt9941 | 150 |

sanchit496 | 109 |

swapnilrawat2017 | 96 |

devesh_goyal | 95 |

saiujwal13083 | 414 |

generic_coder | 304 |

vt9941 | 274 |

ppsvikhyat17 | 244 |

meetpatel0963 | 202 |

Ibrahim Nash | 5438 |

blackshadows | 5428 |

akhayrutdinov | 5111 |

mb1973 | 4976 |

Quandray | 4752 |

Login to report an issue on this page.