text: Rearrange given array such that no array element is same as its index | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrangeArray ( int a [ ] , int n ) { sort ( a , a + n ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ i ] == i + 1 ) { swap ( a [ i ] , a [ i + 1 ] ) ; } } if ( a [ n - 1 ] == n ) { swap ( a [ n - 1 ] , a [ n - 2 ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 2 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrangeArray ( arr , N ) ; return 0 ; }