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
def rearrange ( arr , n ) : NEW_LINE INDENT max_idx = n - 1 NEW_LINE min_idx = 0 NEW_LINE max_elem = arr [ n - 1 ] + 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT arr [ i ] += ( arr [ max_idx ] % max_elem ) * max_elem NEW_LINE max_idx -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] += ( arr [ min_idx ] % max_elem ) * max_elem NEW_LINE min_idx += 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT arr [ i ] = arr [ i ] / max_elem NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Original ▁ Array " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT rearrange ( arr , n ) NEW_LINE print ( " Modified Array " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( int ( arr [ i ] ) , end = " ▁ " ) NEW_LINE DEDENT