Rearrange array to make decimal equivalents of reversed binary representations of array elements sorted | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; } vector < vector < int > > getNew ( vector < int > arr ) { vector < vector < int > > ans ; for ( int i : arr ) ans . push_back ( { keyFunc ( i ) , i } ) ; return ans ; } vector < int > getArr ( vector < vector < int > > arr ) { vector < int > ans ; for ( auto i : arr ) ans . push_back ( i [ 1 ] ) ; return ans ; } void sortArray ( vector < int > arr ) { vector < vector < int > > newArr = getNew ( arr ) ; sort ( newArr . begin ( ) , newArr . end ( ) ) ; arr = getArr ( newArr ) ; int n = arr . size ( ) ; cout << " [ " ; for ( int i = 0 ; i < n - 1 ; i ++ ) cout << arr [ i ] << " , ▁ " ; cout << arr [ n - 1 ] << " ] " ; } int main ( ) { vector < int > arr = { 43 , 52 , 61 , 41 } ; sortArray ( arr ) ; return 0 ; }