TExcelTAD
Home › Sorting & Order Statistics › Tournaments and the Second Smallest

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 lg⁡n\lg n of those. This observation finds the second smallest of nn keys with n+⌈lg⁡n⌉−2n + \lceil \lg n \rceil - 2 comparisons, far fewer than the 2n−32n - 3 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 n−1n - 1 comparisons, remove it, and find the minimum of the remaining n−1n - 1 keys with n−2n - 2 more: 2n−32n - 3 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).

text
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 m

Every match eliminates one key, so the tournament takes exactly n−1n - 1 comparisons. There are ⌈lg⁡n⌉\lceil \lg n \rceil 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 ⌈lg⁡n⌉\lceil \lg n \rceil keys; finding their minimum costs at most ⌈lg⁡n⌉−1\lceil \lg n \rceil - 1 comparisons.

Why the answer is in beaten. Let ss be the second smallest. Every key other than ss that ss could meet is larger than ss, except the minimum mm. So ss wins every match until it meets mm, and it must meet mm eventually, since only one player is left at the end. So ss lost exactly once, to mm, and is in mm's list.

python · try it yourself
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 88 beat 6363, 1717, 1212 and 2121 on its way; the second smallest, 1212, is the smallest of those four. The losing finalist was 2121, which is only the fourth smallest.

In C++

The same tournament on indices, with the beaten lists kept per winner:

cpp · try it yourself
#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 n≤8n \le 8 keys and reports the worst case, next to the formula and the obvious method.

python · try it yourself
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 n=1024n = 1024 the tournament needs 1024+10−2=10321024 + 10 - 2 = 1032 comparisons against 20452045 for the obvious method.

Theorem (Kislitsyn, 1964). Every comparison-based algorithm that finds the second smallest of nn distinct keys makes at least n+⌈lg⁡n⌉−2n + \lceil \lg n \rceil - 2 comparisons in the worst case.

Proof sketch

Two kinds of losses must happen before any algorithm can stop.

  1. Every key other than the minimum must have lost at least once, or it could still be the minimum. That is n−1n - 1 comparisons, one loser each.
  2. Suppose the minimum mm was compared directly with kk keys. Each of them lost to mm, 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 mm: at least k−1k - 1 further comparisons, distinct from the first n−1n - 1 because each of those keys has already used up its first loss on mm.

So at least n−1+k−1n - 1 + k - 1 comparisons are made, and it remains to show that an adversary can force k≥⌈lg⁡n⌉k \ge \lceil \lg n \rceil. 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 nn, 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, nn, which takes at least ⌈lg⁡n⌉\lceil \lg n \rceil comparisons involving it. Together: n+⌈lg⁡n⌉−2n + \lceil \lg n \rceil - 2. (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 ⌈lg⁡n⌉\lceil \lg n \rceil comparisons or fewer, and the new champion is the next smallest. So the kk smallest keys, in order, cost about n+(k−1)⌈lg⁡n⌉n + (k - 1) \lceil \lg n \rceil 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 kk close to n/2n/2, however, klg⁡nk \lg n 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?

  1. Because it plays in the final
  2. 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
  3. Because the bracket is sorted
  4. It need not have

How many comparisons does the tournament method need for the second smallest of n=16n = 16 keys?

  1. 17
  2. 18
  3. 29
  4. 30

Why does the tournament itself make exactly n−1n - 1 comparisons?

  1. Because each comparison eliminates exactly one key and all but one key are eliminated
  2. Because there are lg⁡n\lg n rounds
  3. Because every key plays once
  4. Because of the bye rule