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[0]. 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[0]. 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[0] .

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

  • 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[0]; }
   /* If there are more than one elements, then initialize min and max*/
   if (arr[0] > arr[1]){
      max = arr[0];
      min = arr[1];
   }
   else{
      max = arr[1];
      min = arr[0];
   }
   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
raja
Published on 17-Aug-2020 11:59:53
Advertisements