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 ; Prthe modified array ; Driver Code ; Function Call
code: def rearrangeArray ( a , n ) : NEW_LINE INDENT a = sorted ( a ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( a [ i ] == i + 1 ) : NEW_LINE INDENT a [ i ] , a [ i + 1 ] = a [ i + 1 ] , a [ i ] NEW_LINE DEDENT DEDENT if ( a [ n - 1 ] == n ) : NEW_LINE INDENT a [ n - 1 ] , a [ n - 2 ] = a [ n - 2 ] , a [ n - 1 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 3 , 2 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE rearrangeArray ( arr , N ) NEW_LINE DEDENT