Sort an array according to count of set bits | a utility function that returns total set bits count in an integer ; Function to sort according to bit count . This function assumes that there are 32 bits in an integer . ; Used as an index in final sorted array ; Traverse through all bit counts ( Note that we sort array in decreasing order ) ; Utility function to print an array ; Driver Code
function countBits ( a ) { let count = 0 ; while ( a > 0 ) { if ( ( a & 1 ) > 0 ) count += 1 ; a = a >> 1 ; } return count ; } function sortBySetBitCount ( arr , n ) { let count = new Array ( 32 ) ; for ( let i = 0 ; i < count . length ; i ++ ) count [ i ] = [ ] ; let setbitcount = 0 ; for ( let i = 0 ; i < n ; i ++ ) { setbitcount = countBits ( arr [ i ] ) ; count [ setbitcount ] . push ( arr [ i ] ) ; } let j = 0 ; for ( let i = 31 ; i >= 0 ; i -- ) { let v1 = count [ i ] ; for ( let p = 0 ; p < v1 . length ; p ++ ) arr [ j ++ ] = v1 [ p ] ; } } function printArr ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } let arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] ; let n = arr . length ; sortBySetBitCount ( arr , n ) ; printArr ( arr , n ) ;