Rearrange given array such that no array element is same as its index | Java program for the above approach ; 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 ; Print the modified array ; Driver Code ; Function Call
import java . util . * ; class GFG { static void rearrangeArray ( int a [ ] , int n ) { Arrays . sort ( a ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ i ] == i + 1 ) { int temp = a [ i ] ; a [ i ] = a [ i + 1 ] ; a [ i + 1 ] = temp ; } } if ( a [ n - 1 ] == n ) { int temp = a [ n - 1 ] ; a [ n - 1 ] = a [ n - 2 ] ; a [ n - 2 ] = temp ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( a [ i ] + " ▁ " ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 5 , 3 , 2 , 4 } ; int N = arr . length ; rearrangeArray ( arr , N ) ; } }