Given an integer array, find out the minimum and maximum element present using minimum comparisons.

For example,

Input: nums[] = [5, 7, 2, 4, 9, 6]
 
Output:
 
The minimum array element is 2
The maximum array element is 9

Practice this problem

A naive solution is to compare each array element for minimum and maximum elements by considering a single item at a time. The time complexity of this solution would be linear. The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
The minimum array element is 2
The maximum array element is 9

Performance:

The above solution does 2×(n-1) comparisons in the best case and 3×(n-1) comparisons in the worst case. The worst case happens when all array elements are equal or are sorted in descending order. The best case happens when the input is sorted in ascending order. (Note that we have also considered n-1 comparisons done by for-loop).

Can we do better?

We can improve comparisons done by the above solution by considering elements in pairs. One particular case we need to handle separately when the array has an odd number of items. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
The minimum array element is 1
The maximum array element is 7

Performance:

If the array has an even number of elements n, then the above solution does n/2 + 3n/2 + 2 comparisons in both best and worst-case. (Note that we have also considered n/2 comparisons done by for-loop).

If the array has an odd number of elements n, then the above solution does (n-1)/2 + 3(n-1)/2 + 4 comparisons in both best and worst-case. (We have also considered (n-1)/2 comparisons done by for-loop).