Rearrange array by interchanging positions of even and odd elements in the given array | Function to replace odd elements with even elements and vice versa ; Length of the array ; Traverse the given array ; If arr [ i ] is visited ; Find the next odd element ; Find next even element ; Mark them visited ; Swap them ; Print the final array ; Driver Code ; Given array arr ; Function Call
def swapEvenOdd ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE o = - 1 NEW_LINE e = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT r = - 1 NEW_LINE if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT o += 1 NEW_LINE while ( arr [ o ] % 2 == 0 or arr [ o ] < 0 ) : NEW_LINE INDENT o += 1 NEW_LINE DEDENT r = o NEW_LINE DEDENT else : NEW_LINE INDENT e += 1 NEW_LINE while ( arr [ e ] % 2 == 1 or arr [ e ] < 0 ) : NEW_LINE INDENT e += 1 NEW_LINE DEDENT r = e NEW_LINE DEDENT arr [ i ] *= - 1 NEW_LINE arr [ r ] *= - 1 NEW_LINE tmp = arr [ i ] NEW_LINE arr [ i ] = arr [ r ] NEW_LINE arr [ r ] = tmp NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( ( - 1 * arr [ i ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 4 ] NEW_LINE swapEvenOdd ( arr ) NEW_LINE DEDENT