Sort an array according to count of set bits | Function to count setbits ; Function to sort By SetBitCount ; Iterate over all values and insert into multimap ; Driver Code
def setBitCount ( num ) : NEW_LINE INDENT count = 0 NEW_LINE while ( num ) : NEW_LINE INDENT if ( num & 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT num = num >> 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def sortBySetBitCount ( arr , n ) : NEW_LINE INDENT count = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT count . append ( [ ( - 1 ) * setBitCount ( arr [ i ] ) , arr [ i ] ] ) NEW_LINE DEDENT count . sort ( key = lambda x : x [ 0 ] ) NEW_LINE for i in range ( len ( count ) ) : NEW_LINE INDENT print ( count [ i ] [ 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE sortBySetBitCount ( arr , n ) NEW_LINE