text: Rearrange given array such that no array element is same as its index | Function to rearrange the array a [ ] such that none of the array elements is same as its index ; Sort the array ; Traverse the indices [ 0 , N - 2 ] of the given array ; Check if the current element is equal to its index ; If found to be true , swap current element with the next element ; Check if the last element is same as its index ; If found to be true , swap current element with the previous element ; Prlet the modified array ; Driver code ; Function Call
code: function rearrangeArray ( a , n ) { a . sort ( ) ; for ( let i = 0 ; i < n - 1 ; i ++ ) { if ( a [ i ] == i + 1 ) { let temp = a [ i ] ; a [ i ] = a [ i + 1 ] ; a [ i + 1 ] = temp ; } } if ( a [ n - 1 ] == n ) { let temp = a [ n - 1 ] ; a [ n - 1 ] = a [ n - 2 ] ; a [ n - 2 ] = temp ; } for ( let i = 0 ; i < n ; i ++ ) { document . write ( a [ i ] + " " ) ; } } let arr = [ 1 , 5 , 3 , 2 , 4 ] ; let N = arr . length ; rearrangeArray ( arr , N ) ;