Sort an array according to count of set bits | a utility function that returns total set bits count in an integer ; Function to simultaneously sort both arrays using insertion sort ( http : quiz . geeksforgeeks . org / insertion - sort / ) ; use 2 keys because we need to sort both arrays simultaneously ; Move elements of arr [ 0. . i - 1 ] and aux [ 0. . i - 1 ] , such that elements of aux [ 0. . i - 1 ] are greater than key1 , to one position ahead of their current position ; Function to sort according to bit count using an auxiliary array ; Create an array and store count of set bits in it . ; Sort arr [ ] according to values in aux [ ] ; Utility function to print an array ; Driver Code
def countBits ( a ) : NEW_LINE INDENT count = 0 NEW_LINE while ( a ) : NEW_LINE INDENT if ( a & 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT a = a >> 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def insertionSort ( arr , aux , n ) : NEW_LINE INDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT key1 = aux [ i ] NEW_LINE key2 = arr [ i ] NEW_LINE j = i - 1 NEW_LINE while ( j >= 0 and aux [ j ] < key1 ) : NEW_LINE INDENT aux [ j + 1 ] = aux [ j ] NEW_LINE arr [ j + 1 ] = arr [ j ] NEW_LINE j = j - 1 NEW_LINE DEDENT aux [ j + 1 ] = key1 NEW_LINE arr [ j + 1 ] = key2 NEW_LINE DEDENT DEDENT def sortBySetBitCount ( arr , n ) : NEW_LINE INDENT aux = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT aux [ i ] = countBits ( arr [ i ] ) NEW_LINE DEDENT insertionSort ( arr , aux , n ) NEW_LINE DEDENT def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE sortBySetBitCount ( arr , n ) NEW_LINE printArr ( arr , n ) NEW_LINE DEDENT