Reorder an array according to given indexes | Function to reorder elements of arr [ ] according to index [ ] ; Fix all elements one by one ; While index [ i ] and arr [ i ] are not fixed ; Store values of the target ( or correct ) position before placing arr [ i ] there ; Place arr [ i ] at its target ( or correct ) position . Also copy corrected index for new position ; Copy old target values to arr [ i ] and index [ i ] ; Driver program
function reorder ( arr , index , n ) { for ( let i = 0 ; i < n ; i ++ ) { while ( index [ i ] != i ) { let oldTargetI = index [ index [ i ] ] ; let oldTargetE = arr [ index [ i ] ] ; arr [ index [ i ] ] = arr [ i ] ; index [ index [ i ] ] = index [ i ] ; index [ i ] = oldTargetI ; arr [ i ] = oldTargetE ; } } } let arr = [ 50 , 40 , 70 , 60 , 90 ] ; let index = [ 3 , 0 , 4 , 1 , 2 ] ; let n = arr . length ; reorder ( arr , index , n ) ; document . write ( " " ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; document . write ( " " ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( index [ i ] + " " ) ;