TExcelTAD
Home › Sorting & Order Statistics › Minimum and Maximum Together

Minimum and Maximum Together

Selection starts with its easiest cases. Finding the minimum of nn keys takes n−1n - 1 comparisons, and no algorithm can do with fewer. Finding the maximum as well looks like it should take twice that, 2n−22n - 2. It doesn't: by comparing the keys in pairs first, both can be found with at most 3⌊n/2⌋3 \lfloor n/2 \rfloor 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

text
MINIMUM(a)
1  best = a[0]
2  for i = 1 to n - 1
3      if a[i] < best:  best = a[i]
4  return best

This makes exactly n−1n - 1 comparisons. The decision-tree argument only proves ⌈lg⁡n⌉\lceil \lg n \rceil, because the minimum has only nn possible positions. A sharper argument looks at what each comparison can teach.

Theorem. Every comparison-based algorithm that finds the minimum of nn distinct keys makes at least n−1n - 1 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 n−1n - 1 comparisons are needed.

Both at once: 2n - 2 comparisons naively

Running MINIMUM and then MAXIMUM costs 2(n−1)2(n - 1) 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 2n−22n - 2.

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.

text
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 nn there are n−12\frac{n-1}{2} pairs at 3 comparisons each, 3(n−1)2\frac{3(n-1)}{2} in total. For even nn, one comparison for the first pair and 3 for each of the other n2−1\frac{n}{2} - 1: 3n2−2\frac{3n}{2} - 2. In both cases the count is at most 3⌊n/2⌋3 \lfloor n/2 \rfloor, and it is exactly

⌈3n2⌉−2(n≥1).\left\lceil \frac{3n}{2} \right\rceil - 2 \qquad (n \ge 1).
python · try it yourself
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 n≥2n \ge 2 it is a quarter below 2n−22n - 2.

In C++

cpp · try it yourself
#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 max⁡(⌊32(n−1)⌋,0)\max(\lfloor \frac{3}{2}(n-1) \rfloor, 0) comparisons.)

The lower bound: an adversary argument

Theorem. Every comparison-based algorithm that finds both the minimum and the maximum of n≥2n \ge 2 distinct keys makes at least ⌈3n/2⌉−2\lceil 3n/2 \rceil - 2 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 n≥2n \ge 2) 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 2(n−2)+2=2n−22(n - 2) + 2 = 2n - 2 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 ⌊n/2⌋\lfloor n/2 \rfloor of them, since each uses up two N keys. They provide at most 2⌊n/2⌋2 \lfloor n/2 \rfloor units, and the remaining 2n−2−2⌊n/2⌋2n - 2 - 2\lfloor n/2 \rfloor units need one comparison each. In total at least

⌊n2⌋+2n−2−2⌊n2⌋=2n−2−⌊n2⌋=⌈3n2⌉−2\left\lfloor \frac{n}{2} \right\rfloor + 2n - 2 - 2 \left\lfloor \frac{n}{2} \right\rfloor = 2n - 2 - \left\lfloor \frac{n}{2} \right\rfloor = \left\lceil \frac{3n}{2} \right\rceil - 2

comparisons.

The program checks the matching upper bound by brute force for small nn: over every ordering, the pairing algorithm always returns the true minimum and maximum, and it never uses more than ⌈3n/2⌉−2\lceil 3n/2 \rceil - 2 comparisons.

python · try it yourself
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 nn distinct keys need at least n−1n - 1 comparisons?

  1. Because of the decision-tree bound lg⁡n\lg n
  2. Because every key except the minimum must lose at least one comparison, and each comparison has only one loser
  3. Because the minimum can be anywhere
  4. 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 n=100n = 100 keys?

  1. 148
  2. 150
  3. 198
  4. 99

In MIN-MAX, why is each pair compared with each other first?

  1. To sort the array
  2. 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
  3. To find the median
  4. To make the algorithm stable