You have given n numbers from 1 to n. You have to sort numbers with increasing number of set bits.
for ex: n=5.
output: 1,2,4,3,5
Note: If you have two number with equal number of set bits, then number with lowest value come first in the output.
def sort_by_bits2(n):
array = [x + 1 for x in range(n)]
result = []
while len(result) != n:
for i in range(len(array)):
if array[i] != 0:
array[i] &= (array[i] - 1)
if array[i] == 0:
result.append(i + 1)
return result