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 ; Push the first element to stack ; Iterate the array and swap even and odd ; pop and swap ; print the arr [ ] ; Given array arr ; Length of the arr ; Function Call
function swapEvenOdd ( arr , N ) { let stack = [ ] ; stack . push ( [ 0 , arr [ 0 ] ] ) ; for ( let i = 1 ; i < N ; i ++ ) { if ( stack . length != 0 ) { if ( arr [ i ] % 2 != stack [ stack . length - 1 ] [ 1 ] % 2 ) { let pop = stack . pop ( ) ; let index = pop [ 0 ] , val = pop [ 1 ] ; arr [ index ] = arr [ i ] ; arr [ i ] = val ; } else stack . push ( [ i , arr [ i ] ] ) ; } else stack . push ( [ i , arr [ i ] ] ) ; } for ( let i = 0 ; i < N ; i ++ ) document . write ( arr [ i ] + " " ) ; } let arr = [ 1 , 3 , 2 , 4 ] ; let N = arr . length ; swapEvenOdd ( arr , N ) ;