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
function sortArr ( arr , n ) { let map = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { let count = 0 ; let k = arr [ i ] ; while ( k ) { k = k & k - 1 ; count ++ ; } map . push ( [ 32 - count , arr [ i ] ] ) ; } map . sort ( function ( a , b ) { return a [ 0 ] - b [ 0 ] ; } ) ; for ( let i = 0 ; i < map . length ; i ++ ) { document . write ( map [ i ] [ 1 ] + " " ) ; } } let arr = [ 5 , 2 , 3 , 9 , 4 , 6 , 7 , 15 , 32 ] ; let n = arr . length ; sortArr ( arr , n ) ;