Sort an array according to count of set bits | Set 2 | function to sort the array according to the number of set bits in elements ; Counting no of setBits in arr [ i ] ; The count is subtracted from 32 because the result needs to be in descending order ; Printing the numbers in descending order of set bit count ; Driver code
def sortArr ( arr , n ) : NEW_LINE INDENT mp = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT count = 0 NEW_LINE k = arr [ i ] NEW_LINE while ( k ) : NEW_LINE INDENT k = k & k - 1 NEW_LINE count += 1 NEW_LINE DEDENT mp . append ( ( 32 - count , arr [ i ] ) ) NEW_LINE DEDENT mp . sort ( key = lambda x : x [ 0 ] ) NEW_LINE for it in mp : NEW_LINE INDENT print ( it [ 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 2 , 3 , 9 , 4 , 6 , 7 , 15 , 32 ] NEW_LINE n = len ( arr ) NEW_LINE sortArr ( arr , n ) NEW_LINE DEDENT