Rearrange array by interchanging positions of even and odd elements in the given array | C ++ 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 [ ] ; Driven Program ; Given array arr [ ] ; Stores the length of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swapEvenOdd ( int arr [ ] , int N ) { stack < pair < int , int > > stack ; stack . push ( { 0 , arr [ 0 ] } ) ; for ( int i = 1 ; i < N ; i ++ ) { if ( ! stack . empty ( ) ) { if ( arr [ i ] % 2 != stack . top ( ) . second % 2 ) { pair < int , int > pop = stack . top ( ) ; stack . pop ( ) ; int index = pop . first , val = pop . second ; arr [ index ] = arr [ i ] ; arr [ i ] = val ; } else stack . push ( { i , arr [ i ] } ) ; } else stack . push ( { i , arr [ i ] } ) ; } for ( int i = 0 ; i < N ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; swapEvenOdd ( arr , N ) ; return 0 ; }