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

We are given an array of integers. The task is to find the minimum and maximum elements of the array using the minimum number of comparisons possible.

Syntax

void findMinMax(int arr[], int n, int *min, int *max);

Algorithm

To minimize comparisons, we use an optimized approach −

  • If array has only one element, both min and max are that element
  • For arrays with multiple elements, compare first two elements to initialize min and max
  • Then traverse remaining elements, comparing each with current min and max
  • This approach requires approximately 1.5n comparisons instead of 2n comparisons

Example

Here's a complete program that finds minimum and maximum elements efficiently ?

#include <stdio.h>

void findMinMax(int arr[], int n) {
    int min, max;
    
    // If there is only one element
    if (n == 1) {
        min = max = arr[0];
        printf("Minimum element: %d<br>", min);
        printf("Maximum element: %d<br>", max);
        return;
    }
    
    // Initialize min and max by comparing first two elements
    if (arr[0] > arr[1]) {
        max = arr[0];
        min = arr[1];
    } else {
        max = arr[1];
        min = arr[0];
    }
    
    // Traverse remaining elements
    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<br>", min);
    printf("Maximum element: %d<br>", max);
}

int main() {
    int arr[] = {1, 2, 4, 5, -3, 91};
    int n = 6;
    
    printf("Array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("<br>");
    
    findMinMax(arr, n);
    return 0;
}
Array: 1 2 4 5 -3 91 
Minimum element: -3
Maximum element: 91

Comparison Analysis

Method Comparisons Description
Naive Approach 2(n-1) = 2n-2 Compare each element separately for min and max
Optimized Approach 3n/2 - 2 Compare pairs first, then with min/max

Key Points

  • The optimized approach reduces comparisons from 2n to approximately 1.5n
  • For single element array, no comparisons are needed
  • The algorithm handles both positive and negative numbers correctly

Conclusion

This optimized approach efficiently finds both minimum and maximum elements in approximately 1.5n comparisons, making it more efficient than the naive 2n comparison method for finding min and max separately.

Updated on: 2026-03-15T13:02:31+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements