Find the final sequence of the array after performing given operations | C ++ implementation of the approach ; Function that generates the array b [ ] when n is even ; Fill the first half of the final array with reversed sequence ; Fill the second half ; Function that generates the array b [ ] when n is odd ; Fill the first half of the final array with reversed sequence ; Fill the second half ; Function to find the final array b [ ] after n operations of given type ; Create the array b ; If the array size is even ; Print the final array elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solveEven ( int n , int * arr , int * b ) { int left = n - 1 ; for ( int i = 0 ; i < ( n / 2 ) ; ++ i ) { b [ i ] = arr [ left ] ; left = left - 2 ; if ( left < 0 ) break ; } int right = 0 ; for ( int i = n / 2 ; i <= n - 1 ; ++ i ) { b [ i ] = arr [ right ] ; right = right + 2 ; if ( right > n - 2 ) break ; } } void solveOdd ( int n , int * arr , int * b ) { int left = n - 1 ; for ( int i = 0 ; i < ( n / 2 ) + 1 ; ++ i ) { b [ i ] = arr [ left ] ; left = left - 2 ; if ( left < 0 ) break ; } int right = 1 ; for ( int i = ( n / 2 ) + 1 ; i <= n - 1 ; ++ i ) { b [ i ] = arr [ right ] ; right = right + 2 ; if ( right > n - 2 ) break ; } } void solve ( int n , int * arr ) { int b [ n ] ; if ( n % 2 == 0 ) solveEven ( n , arr , b ) ; else solveOdd ( n , arr , b ) ; for ( int i = 0 ; i <= n - 1 ; ++ i ) { cout << b [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; solve ( n , arr ) ; return 0 ; }