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 ; 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 [ ] ; Length of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N  3 NEW_LINE #define M  4 NEW_LINE void swapEvenOdd ( int arr [ ] , int n ) { 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 ++ ) { cout << ( -1 * arr [ i ] ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; swapEvenOdd ( arr , n ) ; }