Maximum and minimum of an array using minimum number of comparisons | C ++ program of above implementation ; Structure is used to return two values from minMax ( ) ; 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
#include <iostream> NEW_LINE using namespace std ; struct Pair { int min ; int max ; } ; struct Pair getMinMax ( int arr [ ] , int n ) { struct Pair minmax ; int i ; if ( n % 2 == 0 ) { if ( arr [ 0 ] > arr [ 1 ] ) { minmax . max = arr [ 0 ] ; minmax . min = arr [ 1 ] ; } else { minmax . min = arr [ 0 ] ; minmax . max = arr [ 1 ] ; } i = 2 ; } else { minmax . min = arr [ 0 ] ; minmax . max = arr [ 0 ] ; i = 1 ; } while ( i < n - 1 ) { if ( arr [ i ] > arr [ i + 1 ] ) { if ( arr [ i ] > minmax . max ) minmax . max = arr [ i ] ; if ( arr [ i + 1 ] < minmax . min ) minmax . min = arr [ i + 1 ] ; } else { if ( arr [ i + 1 ] > minmax . max ) minmax . max = arr [ i + 1 ] ; if ( arr [ i ] < minmax . min ) minmax . min = arr [ i ] ; } i += 2 ; } return minmax ; } int main ( ) { int arr [ ] = { 1000 , 11 , 445 , 1 , 330 , 3000 } ; int arr_size = 6 ; Pair minmax = getMinMax ( arr , arr_size ) ; cout << " nMinimum ▁ element ▁ is ▁ " << minmax . min << endl ; cout << " nMaximum ▁ element ▁ is ▁ " << minmax . max ; return 0 ; }