Rearrange Odd and Even values in Alternate Fashion in Ascending Order | C ++ implementation of the above approach ; Sort the array ; vector < int > v1 ; to insert even values vector < int > v2 ; to insert odd values ; Set flag to true if first element is even ; Start rearranging array ; If first element is even ; Else , first element is Odd ; Print the rearranged array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void AlternateRearrange ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] % 2 == 0 ) v1 . push_back ( arr [ i ] ) ; else v2 . push_back ( arr [ i ] ) ; int index = 0 , i = 0 , j = 0 ; bool flag = false ; if ( arr [ 0 ] % 2 == 0 ) flag = true ; while ( index < n ) { if ( flag == true ) { arr [ index ++ ] = v1 [ i ++ ] ; flag = ! flag ; } else { arr [ index ++ ] = v2 [ j ++ ] ; flag = ! flag ; } } for ( i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 9 , 8 , 13 , 2 , 19 , 14 } ; int n = sizeof ( arr ) / sizeof ( int ) ; AlternateRearrange ( arr , n ) ; return 0 ; }