Rearrange array to make decimal equivalents of reversed binary representations of array elements sorted | Java program for the above approach ; 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
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int keyFunc ( int n ) { int rev = 0 ; while ( n > 0 ) { rev = rev << 1 ; if ( ( n & 1 ) == 1 ) rev = rev ^ 1 ; n = n >> 1 ; } return rev ; } static int [ ] [ ] getNew ( int arr [ ] ) { int ans [ ] [ ] = new int [ arr . length ] [ 2 ] ; for ( int i = 0 ; i < arr . length ; i ++ ) ans [ i ] = new int [ ] { keyFunc ( arr [ i ] ) , arr [ i ] } ; return ans ; } static int [ ] getArr ( int [ ] [ ] arr ) { int ans [ ] = new int [ arr . length ] ; int idx = 0 ; for ( int i [ ] : arr ) ans [ idx ++ ] = i [ 1 ] ; return ans ; } static void sortArray ( int arr [ ] ) { int [ ] [ ] newArr = getNew ( arr ) ; Arrays . sort ( newArr , ( a , b ) -> { if ( Integer . compare ( a [ 0 ] , b [ 0 ] ) == 0 ) return Integer . compare ( a [ 1 ] , b [ 1 ] ) ; return Integer . compare ( a [ 0 ] , b [ 0 ] ) ; } ) ; arr = getArr ( newArr ) ; int n = arr . length ; System . out . print ( " [ " ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) System . out . print ( arr [ i ] + " , ▁ " ) ; System . out . print ( arr [ n - 1 ] + " ] " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 43 , 52 , 61 , 41 } ; sortArray ( arr ) ; } }