Rearrange array to make decimal equivalents of reversed binary representations of array elements sorted | Function to reverse the bits of a number ; Stores the reversed number ; Divide rev by 2 ; If the value of N is odd ; Update the value of N ; Return the final value of rev ; Function for rearranging the array element according to the given rules ; Stores the new array elements ; Function for rearranging the array ; Stores the new array ; Function to sort the array by reversing binary representation ; Creating a new array ; Sort the array with the key ; Get arr from newArr ; Print the sorted array ; Driver Code
function keyFunc ( n ) { let rev = 0 ; while ( n > 0 ) { rev = rev << 1 ; if ( n & 1 == 1 ) rev = rev ^ 1 ; n = n >> 1 ; } return rev ; } function getNew ( arr ) { let ans = [ ] ; for ( let i of arr ) ans . push ( [ keyFunc ( i ) , i ] ) ; return ans ; } function getArr ( arr ) { let ans = [ ] ; for ( let i of arr ) ans . push ( i [ 1 ] ) ; return ans ; } function sortArray ( arr ) { let newArr = getNew ( arr ) ; newArr . sort ( ) ; arr = getArr ( newArr ) ; let n = arr . length ; document . write ( " " ) ; for ( let i = 0 ; i < n - 1 ; i ++ ) document . write ( arr [ i ] + " " ) ; document . write ( arr [ n - 1 ] + " " ) ; } let arr = [ 43 , 52 , 61 , 41 ] ; sortArray ( arr ) ;