Sorting array elements with set bits equal to K | Utility function ; 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
function bitCount ( x ) { var setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } function sortWithSetbits ( arr , n , k ) { var v1 = [ ] , v2 = [ ] ; for ( var i = 0 ; i < n ; i ++ ) { if ( bitCount ( arr [ i ] ) == k ) { v1 . push ( i ) ; v2 . push ( arr [ i ] ) ; } } v2 . sort ( ( a , b ) => a - b ) ; for ( var i = 0 ; i < v1 . length ; i ++ ) arr [ v1 [ i ] ] = v2 [ i ] ; for ( var i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } var arr = [ 14 , 255 , 1 , 7 , 13 ] ; var n = arr . length ; var k = 3 ; sortWithSetbits ( arr , n , k ) ;