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 ' ; retrieving old value and storing with the new one ; retrieving new value ; A utility function to print contents of arr [ 0. . n - 1 ] ; Driver code
function rearrange ( arr , n ) { for ( i = 0 ; i < n ; i ++ ) { arr [ arr [ i ] % n ] += i * n ; } for ( i = 0 ; i < n ; i ++ ) { arr [ i ] = parseInt ( arr [ i ] / n ) ; } } function printArray ( arr , n ) { for ( i = 0 ; i < n ; i ++ ) { document . write ( arr [ i ] + " " ) ; } document . write ( ) ; } var arr = [ 2 , 0 , 1 , 4 , 5 , 3 ] ; var n = arr . length ; document . write ( " " + " " ) ; printArray ( arr , n ) ; rearrange ( arr , n ) ; document . write ( " " ) document . write ( " " + " " ) ; printArray ( arr , n ) ;