Rearrange an array in maximum minimum form | Set 2 ( O ( 1 ) extra space ) | 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 ; store maximum element of array ; traverse array elements ; at even index : we have to put maximum element ; at odd index : we have to put minimum element ; array elements back to it 's original form ; Driver Code
< ? php function rearrange ( & $ arr , $ n ) { $ max_idx = $ n - 1 ; $ min_idx = 0 ; $ max_elem = $ arr [ $ n - 1 ] + 1 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ i % 2 == 0 ) { $ arr [ $ i ] += ( $ arr [ $ max_idx ] % $ max_elem ) * $ max_elem ; $ max_idx -- ; } else { $ arr [ $ i ] += ( $ arr [ $ min_idx ] % $ max_elem ) * $ max_elem ; $ min_idx ++ ; } } for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ arr [ $ i ] = ( int ) ( $ arr [ $ i ] / $ max_elem ) ; } $ arr = array ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ) ; $ n = sizeof ( $ arr ) ; echo " Original ▁ Array " . " STRNEWLINE " ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; rearrange ( $ arr , $ n ) ; echo " Modified Array " ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ;