Rearrange an array in maximum minimum form | Set 2 ( O ( 1 ) extra space ) | C ++ program to rearrange an array in minimum maximum form ; Prints max at first position , min at second position second max at third position , second min at fourth position and so on . ; initialize index of first minimum and first maximum element ; traverse array elements ; at even index : we have to put maximum element ; at odd index : we have to put minimum element ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrange ( int arr [ ] , int n ) { int max_ele = arr [ n - 1 ] ; int min_ele = arr [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { arr [ i ] = max_ele ; max_ele -= 1 ; } else { arr [ i ] = min_ele ; min_ele += 1 ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Original ▁ Array STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; rearrange ( arr , n ) ; cout << " Modified Array " for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }