Rearrange an array such that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' | Set 1 | A simple C ++ program to rearrange contents of arr [ ] such that arr [ j ] becomes j if arr [ i ] is j ; A simple method to rearrange ' arr [ 0 . . n - 1 ] ' so that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' ; Create an auxiliary array of same size ; Store result in temp [ ] ; Copy temp back to arr [ ] ; A utility function to print contents of arr [ 0. . n - 1 ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrangeNaive ( int arr [ ] , int n ) { int temp [ n ] , i ; for ( i = 0 ; i < n ; i ++ ) temp [ arr [ i ] ] = i ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = temp [ i ] ; } void printArray ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; i ++ ) cout << ( " % d ▁ " , arr [ i ] ) ; cout << ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 0 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( " Given ▁ array ▁ is ▁ STRNEWLINE " ) ; printArray ( arr , n ) ; rearrangeNaive ( arr , n ) ; cout << ( " Modified ▁ array ▁ is ▁ STRNEWLINE " ) ; printArray ( arr , n ) ; return 0 ; }