Minimum and maximum together
Take the items in pairs: the smaller of a pair is compared only with the minimum and the larger only with the maximum; 3 comparisons per 2 items.
Finding the minimum alone takes n − 1 comparisons, and so does the maximum; done separately that is 2n − 2. The
trick is to take the items in pairs. First compare the two items of the pair with each other; the smaller can
only be the minimum and the larger only the maximum. So every two items need just 3 comparisons.
- Time:
about 3n/2 comparisons - Space:
O(1) - CLRS, section 9.1
- Johnsonbaugh, chapter 4
Eight numbers: 1 comparison for the first pair and 3 for each of the next three pairs, 10 in all instead of 14.
def min_max(a):n = len(a)if n % 2 == 1:lo = a[0]hi = a[0]start = 1else:if a[0] < a[1]:lo = a[0]hi = a[1]else:lo = a[1]hi = a[0]start = 2for i in range(start, n - 1, 2):if a[i] < a[i + 1]:small = a[i]big = a[i + 1]else:small = a[i + 1]big = a[i]if small < lo:lo = smallif big > hi:hi = bigreturn lo, hi
Start
Local variables
Orange = changed in this step
a list
Call stack
- min_max()line 1
How the work grows with input size
Average of 12 random graphs per n (fixed seeds). Hollow marker = the input on screen.
- comparisons
- current input (n=8)
Show as a table
| n | comparisons |
|---|---|
| 4 | 4 |
| 6 | 7 |
| 8 | 10 |
| 10 | 13 |
| 12 | 16 |
| 14 | 19 |
| 16 | 22 |
Explanation
The idea
Finding the minimum alone takes n − 1 comparisons, and so does the maximum; done separately that is 2n − 2. The
trick is to take the items in pairs. First compare the two items of the pair with each other; the smaller can
only be the minimum and the larger only the maximum. So every two items need just 3 comparisons.
Cost
At most 3⌊n/2⌋ comparisons, about 1.5n instead of 2n. This is also optimal: no comparison-based algorithm can
find both with fewer than ⌈3n/2⌉ − 2 comparisons.
What to watch in the trace
- The
iarrow marks the first item of each pair;loandhiare in the memory panel. - Compare the number of
comparesteps with2n − 2.