text: 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 program
code: #include <stdio.h> NEW_LINE 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 ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 0 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Given ▁ array ▁ is ▁ STRNEWLINE " ) ; printArray ( arr , n ) ; rearrangeNaive ( arr , n ) ; printf ( " Modified ▁ array ▁ is ▁ STRNEWLINE " ) ; printArray ( arr , n ) ; return 0 ; }