# Maximum and minimum of an array using minimum number of comparisons in C

CServer Side ProgrammingProgramming

We are given with an array of integers. The task is to find the minimum and maximum element of the array in the minimum number of comparisons.

Input

Arr[] = { 1,2,4,5,-3,91 }

Output

Maximum element : 91 Minimum Element : -3

Explanation − Here to minimize the number of comparisons, we will initialize the maximum and minimum element with Arr. And starting from the 2nd element compare each value with min and max and update accordingly.

Input

Arr[] = { 10,20,21,31,18,11 }

Output

Maximum element : 31 Minimum Element : 10

Explanation − Here also, to minimize the number of comparisons, we will initialize the maximum and minimum element with Arr. And starting from the 2nd element compare each value with min and max and update accordingly.

## Approach used in the below program is as follows

• We take an integer array having numbers as Arr[]

• The function getresult( int arr[],int n) is to find the maximum and minimum element present in the array in minimum no. of comparisons.

• If there is only one element then we will initialize the variables max and min with arr .

• For more than one element, we will initialize max with arr and min with arr.

• Inside for loop start traversing from third element ( i=2 ) till last.

• Now we will compare each value ( arr[i] ) with min and max. If it is less than min, update min with arr[i]. If it is more than max, then update max with arr[i].

• In the end print the results stored in max and min variables.

## Example

Live Demo

#include <stdio.h>
#include <math.h>
int getresult(int arr[], int n){
int min=0,max=0;
/*If there is only one element then return it as min and max both*/
if (n == 1)
{ min=max=arr; }
/* If there are more than one elements, then initialize min and max*/
if (arr > arr){
max = arr;
min = arr;
}
else{
max = arr;
min = arr;
}
for (int i = 2; i<n; i++){
if (arr[i] > max)
max = arr[i];
else if (arr[i] < min)
min = arr[i];
}
printf(" Minimum element: %d", min);
printf(" Maximum element: %d", max);
}
/* Driver program to test above function */
int main(){
int arr[] = {200, 191, 112, -11, 330, 60};
int n = 6;
getresult (arr, n);
}

## Output

If we run the above code it will generate the following output −

Minimum element: -11 Maximum element: 330