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 ; Push the first element to stack ; iterate the array and swap even and odd ; pop and swap ; print the arr [ ] ; Driver code ; Given array arr ; length of the arr ; Function Call
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void swapEvenOdd ( int arr [ ] , int N ) { Stack < int [ ] > stack = new Stack < > ( ) ; stack . push ( new int [ ] { 0 , arr [ 0 ] } ) ; for ( int i = 1 ; i < N ; i ++ ) { if ( ! stack . isEmpty ( ) ) { if ( arr [ i ] % 2 != stack . peek ( ) [ 1 ] % 2 ) { int pop [ ] = stack . pop ( ) ; int index = pop [ 0 ] , val = pop [ 1 ] ; arr [ index ] = arr [ i ] ; arr [ i ] = val ; } else stack . push ( new int [ ] { i , arr [ i ] } ) ; } else stack . push ( new int [ ] { i , arr [ i ] } ) ; } for ( int i = 0 ; i < N ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; int N = arr . length ; swapEvenOdd ( arr , N ) ; } }