Sorting array elements with set bits equal to K | Function to sort elements with set bits equal to k ; initialise two vectors ; first vector contains indices of required element ; second vector contains required elements ; sorting the elements in second vector ; replacing the elements with k set bits with the sorted elements ; printing the new sorted array elements ; Driver code
def sortWithSetbits ( arr , n , k ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( bin ( arr [ i ] ) . count ( '1' ) == k ) : NEW_LINE INDENT v1 . append ( i ) NEW_LINE v2 . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT v2 . sort ( reverse = False ) NEW_LINE for i in range ( 0 , len ( v1 ) , 1 ) : NEW_LINE INDENT arr [ v1 [ i ] ] = v2 [ i ] NEW_LINE DEDENT 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 = [ 14 , 255 , 1 , 7 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE sortWithSetbits ( arr , n , k ) NEW_LINE DEDENT