Minimum and Maximum Together
Selection starts with its easiest cases. Finding the minimum of keys takes comparisons, and no algorithm can do with fewer. Finding the maximum as well looks like it should take twice that, . It doesn't: by comparing the keys in pairs first, both can be found with at most comparisons, a saving of a quarter. And a lower-bound argument of a new kind, the adversary argument, shows that this is optimal.
These are small results, but they set the pattern for the rest of the section: count comparisons exactly, then prove that nothing can do better.
The minimum: n - 1 comparisons, and why that is optimal
MINIMUM(a)
1 best = a[0]
2 for i = 1 to n - 1
3 if a[i] < best: best = a[i]
4 return bestThis makes exactly comparisons. The decision-tree argument only proves , because the minimum has only possible positions. A sharper argument looks at what each comparison can teach.
Theorem. Every comparison-based algorithm that finds the minimum of distinct keys makes at least comparisons.
Proof. Think of each comparison as a game between two keys, and call the larger one the loser. A key that has never lost might still be the minimum, as far as the algorithm knows: changing it to a value below everything else would agree with every comparison made, and it would then be the minimum. So when the algorithm stops, every key except the answer must have lost at least once. Each comparison produces exactly one loser, so at least comparisons are needed.
Both at once: 2n - 2 comparisons naively
Running MINIMUM and then MAXIMUM costs comparisons. A simple improvement compares each new key with the minimum, and with the maximum only if it was not a new minimum, but in the worst case (increasing input, where no key is a new minimum) it still makes .
Pairs: at most 3 floor(n/2) comparisons
Process the keys two at a time. Compare the two keys of a pair with each other first. Then only the smaller one can be a new minimum and only the larger one can be a new maximum, so each pair costs 3 comparisons instead of 4.
MIN-MAX(a)
1 if n is odd: lo = hi = a[0], start = 1 // 0 comparisons
2 else: lo, hi = the smaller and larger of a[0], a[1], start = 2 // 1 comparison
3 for i = start to n - 2 step 2
4 if a[i] < a[i + 1]: small, large = a[i], a[i + 1]
5 else: small, large = a[i + 1], a[i]
6 if small < lo: lo = small
7 if large > hi: hi = large
8 return (lo, hi)Counting: for odd there are pairs at 3 comparisons each, in total. For even , one comparison for the first pair and 3 for each of the other : . In both cases the count is at most , and it is exactly
def min_max(a):
comparisons = 0
n = len(a)
if n % 2 == 1:
lo = hi = a[0]; start = 1
else:
comparisons += 1
lo, hi = (a[0], a[1]) if a[0] < a[1] else (a[1], a[0]); start = 2
for i in range(start, n - 1, 2):
comparisons += 1
small, large = (a[i], a[i + 1]) if a[i] < a[i + 1] else (a[i + 1], a[i])
comparisons += 1
if small < lo: lo = small
comparisons += 1
if large > hi: hi = large
return lo, hi, comparisons
def min_then_max(a):
lo = hi = a[0]
comparisons = 0
for x in a[1:]:
comparisons += 1
if x < lo: lo = x
for x in a[1:]:
comparisons += 1
if x > hi: hi = x
return lo, hi, comparisons
a = [31, 7, 19, 4, 26, 12, 40, 15, 9]
print("pairs: ", min_max(a))
print("min, then max: ", min_then_max(a))
for n in range(1, 11):
data = list(range(n, 0, -1))
c = min_max(data)[2]
print(f"n = {n:>2}: {c:>2} comparisons, ceil(3n/2) - 2 = {(3 * n + 1) // 2 - 2:>2}, 3 floor(n/2) = {3 * (n // 2):>2}, 2n - 2 = {2 * n - 2:>2}")pairs: (4, 40, 12)
min, then max: (4, 40, 16)
n = 1: 0 comparisons, ceil(3n/2) - 2 = 0, 3 floor(n/2) = 0, 2n - 2 = 0
n = 2: 1 comparisons, ceil(3n/2) - 2 = 1, 3 floor(n/2) = 3, 2n - 2 = 2
n = 3: 3 comparisons, ceil(3n/2) - 2 = 3, 3 floor(n/2) = 3, 2n - 2 = 4
n = 4: 4 comparisons, ceil(3n/2) - 2 = 4, 3 floor(n/2) = 6, 2n - 2 = 6
n = 5: 6 comparisons, ceil(3n/2) - 2 = 6, 3 floor(n/2) = 6, 2n - 2 = 8
n = 6: 7 comparisons, ceil(3n/2) - 2 = 7, 3 floor(n/2) = 9, 2n - 2 = 10
n = 7: 9 comparisons, ceil(3n/2) - 2 = 9, 3 floor(n/2) = 9, 2n - 2 = 12
n = 8: 10 comparisons, ceil(3n/2) - 2 = 10, 3 floor(n/2) = 12, 2n - 2 = 14
n = 9: 12 comparisons, ceil(3n/2) - 2 = 12, 3 floor(n/2) = 12, 2n - 2 = 16
n = 10: 13 comparisons, ceil(3n/2) - 2 = 13, 3 floor(n/2) = 15, 2n - 2 = 18
The count does not depend on the data: the algorithm makes the same number of comparisons on every input of a given size, and for it is a quarter below .
In C++
#include <cstdio>
#include <utility>
#include <vector>
struct MinMax { int lo, hi, comparisons; };
MinMax min_max(const std::vector<int>& a) {
int n = static_cast<int>(a.size()), c = 0, lo, hi, start;
if (n % 2 == 1) { lo = hi = a[0]; start = 1; }
else { ++c; lo = std::min(a[0], a[1]); hi = std::max(a[0], a[1]); start = 2; }
for (int i = start; i + 1 < n; i += 2) {
int small = a[i], large = a[i + 1];
++c; if (large < small) std::swap(small, large);
++c; if (small < lo) lo = small;
++c; if (large > hi) hi = large;
}
return {lo, hi, c};
}
int main() {
std::vector<int> a = {31, 7, 19, 4, 26, 12, 40, 15, 9};
MinMax r = min_max(a);
std::printf("min %d, max %d, %d comparisons\n", r.lo, r.hi, r.comparisons);
std::vector<int> b = {5, 8, 1, 9, 3, 2, 7, 6, 4, 0};
r = min_max(b);
std::printf("min %d, max %d, %d comparisons\n", r.lo, r.hi, r.comparisons);
}min 4, max 40, 12 comparisons
min 0, max 9, 13 comparisons
(std::minmax_element in the C++ standard library uses the same pairing idea and is specified to make at most comparisons.)
The lower bound: an adversary argument
Theorem. Every comparison-based algorithm that finds both the minimum and the maximum of distinct keys makes at least comparisons in the worst case.
So the pairing algorithm is exactly optimal. The proof uses an adversary: instead of fixing the input in advance, imagine an opponent who answers each comparison so as to keep the algorithm ignorant as long as possible, while making sure the answers are always consistent with some real input.
Proof sketch
In every comparison call the larger key the winner. A key that has never lost could still be the maximum, and a key that has never won could still be the minimum. When the algorithm stops, exactly one key may be unbeaten (the maximum) and exactly one may be winless (the minimum). So every other key must have won at least once and lost at least once, the maximum must have won (as ) and the minimum must have lost.
Count units of information: one unit for each key's first win and one for its first loss. The end state needs units. Track each key's state: N (never compared), W (won, never lost), L (lost, never won), WL (both).
The adversary answers so that each comparison gives as few units as possible, choosing values for the keys as it goes so that its answers always fit a real input:
- comparing two N keys gives 2 units (one becomes W, the other L), and nothing can prevent that;
- every other comparison can be answered so that it gives at most 1 unit. For example, N against W: the W key wins again, and only the N key gains a unit; W against L: the W key wins, and nobody gains anything.
Only comparisons between two N keys give 2 units, and there can be at most of them, since each uses up two N keys. They provide at most units, and the remaining units need one comparison each. In total at least
comparisons.
The program checks the matching upper bound by brute force for small : over every ordering, the pairing algorithm always returns the true minimum and maximum, and it never uses more than comparisons.
from itertools import permutations
def min_max(a):
c, n = 0, len(a)
if n % 2: lo = hi = a[0]; start = 1
else:
c += 1; lo, hi = min(a[0], a[1]), max(a[0], a[1]); start = 2
for i in range(start, n - 1, 2):
c += 3
small, large = min(a[i], a[i + 1]), max(a[i], a[i + 1])
lo, hi = min(lo, small), max(hi, large)
return lo, hi, c
for n in range(2, 9):
worst = 0
for p in permutations(range(n)):
lo, hi, c = min_max(list(p))
assert (lo, hi) == (0, n - 1)
worst = max(worst, c)
print(f"n = {n}: all {len(list(permutations(range(n))))} orderings correct, comparisons {worst}, bound ceil(3n/2) - 2 = {(3 * n + 1) // 2 - 2}")n = 2: all 2 orderings correct, comparisons 1, bound ceil(3n/2) - 2 = 1
n = 3: all 6 orderings correct, comparisons 3, bound ceil(3n/2) - 2 = 3
n = 4: all 24 orderings correct, comparisons 4, bound ceil(3n/2) - 2 = 4
n = 5: all 120 orderings correct, comparisons 6, bound ceil(3n/2) - 2 = 6
n = 6: all 720 orderings correct, comparisons 7, bound ceil(3n/2) - 2 = 7
n = 7: all 5040 orderings correct, comparisons 9, bound ceil(3n/2) - 2 = 9
n = 8: all 40320 orderings correct, comparisons 10, bound ceil(3n/2) - 2 = 10
Test yourself
Why does finding the minimum of distinct keys need at least comparisons?
- Because of the decision-tree bound
- Because every key except the minimum must lose at least one comparison, and each comparison has only one loser
- Because the minimum can be anywhere
- Because each key must be compared with every other key
How many comparisons does the pairing algorithm make to find both the minimum and maximum of keys?
- 148
- 150
- 198
- 99
In MIN-MAX, why is each pair compared with each other first?
- To sort the array
- So that only the smaller key is compared with the minimum and only the larger with the maximum: 3 comparisons per pair instead of 4
- To find the median
- To make the algorithm stable