Rearrange an array such that arr [ i ] = i | Function to tranform the array ; Iterate over the array ; Check is any ar [ j ] exists such that ar [ j ] is equal to i ; Iterate over array ; If not present ; Print the output ; Driver Code ; Function Call
function fixArray ( ar , n ) { var i , j , temp ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { if ( ar [ j ] == i ) { temp = ar [ j ] ; ar [ j ] = ar [ i ] ; ar [ i ] = temp ; break ; } } } for ( i = 0 ; i < n ; i ++ ) { if ( ar [ i ] != i ) { ar [ i ] = - 1 ; } } document . write ( " " ) ; document . write ( " " ) ; for ( i = 0 ; i < n ; i ++ ) { document . write ( ar [ i ] + " " ) ; } } var n , ar = [ - 1 , - 1 , 6 , 1 , 9 , 3 , 2 , - 1 , 4 , - 1 ] ; n = ar . length ; fixArray ( ar , n ) ;