Maximum and minimum of an array using minimum number of comparisons | getMinMax ( ) ; If array has even number of elements then initialize the first two elements as minimum and maximum ; set the starting index for loop ; If array has odd number of elements then initialize the first element as minimum and maximum ; set the starting index for loop ; In the while loop , pick elements in pair and compare the pair with max and min so far ; Increment the index by 2 as two elements are processed in loop ; Driver Code
def getMinMax ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT mx = max ( arr [ 0 ] , arr [ 1 ] ) NEW_LINE mn = min ( arr [ 0 ] , arr [ 1 ] ) NEW_LINE i = 2 NEW_LINE DEDENT else : NEW_LINE INDENT mx = mn = arr [ 0 ] NEW_LINE i = 1 NEW_LINE DEDENT while ( i < n - 1 ) : NEW_LINE INDENT if arr [ i ] < arr [ i + 1 ] : NEW_LINE INDENT mx = max ( mx , arr [ i + 1 ] ) NEW_LINE mn = min ( mn , arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT mx = max ( mx , arr [ i ] ) NEW_LINE mn = min ( mn , arr [ i + 1 ] ) NEW_LINE DEDENT i += 2 NEW_LINE DEDENT return ( mx , mn ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1000 , 11 , 445 , 1 , 330 , 3000 ] NEW_LINE mx , mn = getMinMax ( arr ) NEW_LINE print ( " Minimum ▁ element ▁ is " , mn ) NEW_LINE print ( " Maximum ▁ element ▁ is " , mx ) NEW_LINE DEDENT