![]() |
VOOZH | about |
Given an array of integers arr[], the task is to find the maximum and minimum elements in the array using the minimum number of comparisons.
Examples:
Input: arr[] = [3, 5, 4, 1, 9]
Output: [1, 9]
Explanation: The minimum element is 1, and the maximum element is 9.Input: arr[] = [22, 14, 8, 17, 35, 3]
Output: [3, 35]
Explanation: The minimum element is 3, and the maximum element is 35.
Table of Content
The idea is to firstly sort the array in ascending order.
Once the array is sorted, the first element of the array will be the minimum element and the last element of the array will be the maximum element.
The number of comparisons is equal to the number of comparisons made during the sorting process. For any comparison-based sorting algorithm, the minimum number of comparisons required in the worst case to sort an array of n elements is O(n log n). Hence, the number of comparisons made in this approach is O(n log n).
1 9
The idea is to perform a single traversal, firstly initialize two variables - mini as INT_MAX and maxi as INT_MIN, then traverse the array to update mini whenever a smaller element is encountered and to update maxi whenever a larger element is found.
1 9
This method recursively divides the array until it can no longer be split. If a segment contains only one element, that element is both the minimum and maximum. If it contains two elements, they are compared directly. For larger segments, the method finds the min and max in each half, then combines the results by taking the smaller of the two minimums and the larger of the two maximums.
Let T(n) be the number of comparisons needed for an array of size n.
- If there's 1 element: T(1) = 0 (no comparison needed).
- If there are 2 elements: T(2) = 1 (just 1 comparison).
- For larger arrays: the method splits the array, recursively compares each half, and adds 2 comparisons to combine results:
T(n) = T(floor(n / 2)) + T(ceil(n / 2)) + 2
When n is a power of 2, solving this gives:
T(n) = (3 * n) / 2 - 2
Below is the implementation of the above approach:
1 9
This approach finds the smallest and largest numbers in a list by reducing the number of comparisons. If the list has an odd number of elements, it initializes both the minimum and maximum with the first element. If it has an even number, it compares the first two elements to set the initial min and max.
It then processes the remaining elements in pairs. For each pair, it identifies the smaller and larger number, then updates the current minimum and maximum accordingly. After all pairs are checked, the final minimum and maximum values are returned.
If n is odd:
If n is even:
Below is the implementation of the above approach:
1 9