Tournaments and the Second Smallest
Who is the second-best player in a knockout tournament? Not necessarily the losing finalist: the second-best player might have met the champion in the first round. But the second-best player can only have lost to one person, the champion. So the second-best is among the players the champion beat, and there are only about of those. This observation finds the second smallest of keys with comparisons, far fewer than the of the obvious method, and that number is exactly optimal.
The lesson continues Minimum and Maximum Together: small selection problems, solved with an exact comparison count and a matching lower bound.
The obvious method
Find the minimum with comparisons, remove it, and find the minimum of the remaining keys with more: in total. The second scan wastes almost everything the first one learned. In particular, every key that lost to something other than the minimum during the first scan is known not to be second smallest, yet the second scan compares it again.
The tournament
Run the minimum search as a knockout tournament: pair the keys up, the smaller of each pair advances, repeat until one key remains. A key without a partner in some round advances for free (a bye).
TOURNAMENT-SECOND-SMALLEST(a) // n >= 2 distinct keys
1 players = [(x, []) for each x in a] // (key, list of keys it has beaten)
2 while more than one player remains
3 pair the players up in order; a leftover player advances unchanged
4 for each pair (x, bx), (y, by)
5 if x < y: advance (x, bx + [y]) else advance (y, by + [x])
6 (m, beaten) = the last player // m is the minimum
7 return the minimum of beaten // the second smallest lost directly to mEvery match eliminates one key, so the tournament takes exactly comparisons. There are rounds (each round halves the number of players, rounding up), and the champion plays at most one match per round, so beaten has at most keys; finding their minimum costs at most comparisons.
Why the answer is in beaten. Let be the second smallest. Every key other than that could meet is larger than , except the minimum . So wins every match until it meets , and it must meet eventually, since only one player is left at the end. So lost exactly once, to , and is in 's list.
def second_smallest(a, trace=False):
comparisons = 0
players = [(x, []) for x in a]
rnd = 1
while len(players) > 1:
nxt = []
for i in range(0, len(players) - 1, 2):
(x, bx), (y, by) = players[i], players[i + 1]
comparisons += 1
nxt.append((x, bx + [y]) if x < y else (y, by + [x]))
if len(players) % 2:
nxt.append(players[-1]) # bye
players = nxt
if trace:
print(f"after round {rnd}: {[p[0] for p in players]}")
rnd += 1
m, beaten = players[0]
best = beaten[0]
for x in beaten[1:]:
comparisons += 1
if x < best:
best = x
if trace:
print(f"minimum {m} beat {beaten}")
return m, best, comparisons
a = [41, 17, 63, 8, 29, 12, 55, 34, 21, 70]
m, s, c = second_smallest(a, trace=True)
print(f"second smallest {s}, {c} comparisons (obvious method: {2 * len(a) - 3})")after round 1: [17, 8, 12, 34, 21]
after round 2: [8, 12, 21]
after round 3: [8, 21]
after round 4: [8]
minimum 8 beat [63, 17, 12, 21]
second smallest 12, 12 comparisons (obvious method: 17)
The minimum beat , , and on its way; the second smallest, , is the smallest of those four. The losing finalist was , which is only the fourth smallest.
In C++
The same tournament on indices, with the beaten lists kept per winner:
#include <cmath>
#include <cstdio>
#include <vector>
int main() {
std::vector<int> a = {41, 17, 63, 8, 29, 12, 55, 34, 21, 70};
int n = static_cast<int>(a.size()), comparisons = 0;
std::vector<std::vector<int>> beaten(n); // beaten[i] = keys that a[i] has beaten
std::vector<int> players(n);
for (int i = 0; i < n; ++i) players[i] = i;
while (players.size() > 1) {
std::vector<int> next;
for (std::size_t i = 0; i + 1 < players.size(); i += 2) {
int x = players[i], y = players[i + 1];
++comparisons;
int w = a[x] < a[y] ? x : y, l = w == x ? y : x;
beaten[w].push_back(a[l]);
next.push_back(w);
}
if (players.size() % 2) next.push_back(players.back());
players = next;
}
int m = players[0], second = beaten[m][0];
for (std::size_t i = 1; i < beaten[m].size(); ++i) {
++comparisons;
if (beaten[m][i] < second) second = beaten[m][i];
}
std::printf("minimum %d, second smallest %d, %d comparisons, n + ceil(lg n) - 2 = %d\n",
a[m], second, comparisons, n + static_cast<int>(std::ceil(std::log2(n))) - 2);
}minimum 8, second smallest 12, 12 comparisons, n + ceil(lg n) - 2 = 12
Exact count and optimality
The program checks the tournament on every ordering of keys and reports the worst case, next to the formula and the obvious method.
import math
from itertools import permutations
def second_smallest(a):
c, players = 0, [(x, []) for x in a]
while len(players) > 1:
nxt = []
for i in range(0, len(players) - 1, 2):
(x, bx), (y, by) = players[i], players[i + 1]
c += 1
nxt.append((x, bx + [y]) if x < y else (y, by + [x]))
if len(players) % 2: nxt.append(players[-1])
players = nxt
m, beaten = players[0]
c += len(beaten) - 1
return min(beaten), c
for n in range(2, 9):
worst = 0
for p in permutations(range(n)):
s, c = second_smallest(list(p))
assert s == 1
worst = max(worst, c)
print(f"n = {n}: worst {worst:>2} comparisons, n + ceil(lg n) - 2 = {n + math.ceil(math.log2(n)) - 2:>2}, 2n - 3 = {2 * n - 3:>2}")n = 2: worst 1 comparisons, n + ceil(lg n) - 2 = 1, 2n - 3 = 1
n = 3: worst 3 comparisons, n + ceil(lg n) - 2 = 3, 2n - 3 = 3
n = 4: worst 4 comparisons, n + ceil(lg n) - 2 = 4, 2n - 3 = 5
n = 5: worst 6 comparisons, n + ceil(lg n) - 2 = 6, 2n - 3 = 7
n = 6: worst 7 comparisons, n + ceil(lg n) - 2 = 7, 2n - 3 = 9
n = 7: worst 8 comparisons, n + ceil(lg n) - 2 = 8, 2n - 3 = 11
n = 8: worst 9 comparisons, n + ceil(lg n) - 2 = 9, 2n - 3 = 13
For the tournament needs comparisons against for the obvious method.
Theorem (Kislitsyn, 1964). Every comparison-based algorithm that finds the second smallest of distinct keys makes at least comparisons in the worst case.
Proof sketch
Two kinds of losses must happen before any algorithm can stop.
- Every key other than the minimum must have lost at least once, or it could still be the minimum. That is comparisons, one loser each.
- Suppose the minimum was compared directly with keys. Each of them lost to , and that loss says nothing about whether it is second smallest. So all of them except the answer must also have lost to some key other than : at least further comparisons, distinct from the first because each of those keys has already used up its first loss on .
So at least comparisons are made, and it remains to show that an adversary can force . Give every key a weight of 1. When two keys that have never lost are compared, the adversary declares the heavier one smaller (either one on a tie) and the winner takes over the loser's weight; in every other comparison it answers consistently with earlier answers and moves no weight. The weights always sum to , and a key's weight at most doubles in each comparison it wins. At the end every other key has lost, so the minimum holds all the weight, , which takes at least comparisons involving it. Together: . (A full proof is in Knuth's The Art of Computer Programming, volume 3, section 5.3.3.)
From second smallest to k smallest
The tournament tree can be reused: after removing the champion, replay only the matches on its path, which takes comparisons or fewer, and the new champion is the next smallest. So the smallest keys, in order, cost about comparisons. This is exactly what heapsort's extraction phase does with a heap (Heapsort), with one difference: a tournament tree stores the keys at the leaves and the winners at internal nodes, which uses twice the memory but needs only one comparison per level instead of two. Tournament trees are used in practice to merge many sorted runs on disk.
For close to , however, is too much. Finding the median needs a different idea, which the next two lessons develop: Randomized Quickselect and Median of Medians.
Test yourself
In a knockout tournament for the minimum, why must the second smallest key have lost to the minimum?
- Because it plays in the final
- Because it beats every other key, so the only match it can lose is against the minimum, and only one player remains at the end
- Because the bracket is sorted
- It need not have
How many comparisons does the tournament method need for the second smallest of keys?
- 17
- 18
- 29
- 30
Why does the tournament itself make exactly comparisons?
- Because each comparison eliminates exactly one key and all but one key are eliminated
- Because there are rounds
- Because every key plays once
- Because of the bye rule