Rearrange an array such that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' | Set 1 | 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
function rearrangeNaive ( arr , n ) { let temp = new Array ( n ) , i ; for ( i = 0 ; i < n ; i ++ ) temp [ arr [ i ] ] = i ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = temp [ i ] ; } function printArray ( arr , n ) { let i ; for ( i = 0 ; i < n ; i ++ ) document . write ( " " + arr [ i ] ) ; document . write ( " " ) ; } let arr = [ 1 , 3 , 0 , 2 ] ; let n = arr . length ; document . write ( " " ) ; printArray ( arr , n ) ; rearrangeNaive ( arr , n ) ; document . write ( " " ) ; printArray ( arr , n ) ;