Rearrange array by interchanging positions of even and odd elements in the given array | Java program for the above approach ; 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
import java . io . * ; class GFG { static void swapEvenOdd ( int arr [ ] ) { int n = arr . length ; int o = - 1 , e = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) continue ; int r = - 1 ; if ( arr [ i ] % 2 == 0 ) { o ++ ; while ( arr [ o ] % 2 == 0 arr [ o ] < 0 ) o ++ ; r = o ; } else { e ++ ; while ( arr [ e ] % 2 == 1 arr [ e ] < 0 ) e ++ ; r = e ; } arr [ i ] *= - 1 ; arr [ r ] *= - 1 ; int tmp = arr [ i ] ; arr [ i ] = arr [ r ] ; arr [ r ] = tmp ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ( - 1 * arr [ i ] ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; swapEvenOdd ( arr ) ; } }