← All problemsFree · Python · 50 min

Algorithm design / guarantees under an adversary

The Pivot from Group Medians

Build the inputs that push the median-of-medians pivot as far off-centre as it can go, count exactly how far, and find which group sizes still give a linear-time selection algorithm.

0 / 4 graded parts passSaved in this browser · loading saved work…
Jump to your work ↓

A quality lab weighs n samples and needs the one of rank k: the median, say. Sorting all n is wasteful. Selection by pivoting is fast when the pivot lands near the middle, and slow when an input pushes it to one side.

n = 15, g = 5: 3 groups, each group's median marked, the pivot boxedgroup 1417296318group 2551270343group 3264896137the group medians, in order:293437pivot = the 2nd smallest of the 3 medians = 34selection keeps one side of the pivot and recurses
The rule on 15 numbers with g = 5.

The median-of-medians rule picks a pivot that no input can push too far. It works with a group size g (here n is always a multiple of g):

  1. Split the list into consecutive groups of g: positions 0 to g−1, then g to 2g−1, and so on. There are q=n/g groups.
  2. Take each group's median: its ⌈g/2⌉-th smallest element (for even g, the lower of the two middle elements).
  3. The pivot is the median of those q medians: their ⌈q/2⌉-th smallest.

Selection then discards every element on the wrong side of the pivot and recurses on the rest, which is linear time overall if the pivot is never too far off-centre. Textbooks use g=5. Why 5? What goes wrong with 3, and is 5 the only choice?

All the numbers in a list are different. "Smaller than the pivot" counts elements strictly smaller.

Background: Selection in Linear Time.

easy · Part A

A bad pivot from groups of 3

With g=3 and n=27, give 27 different whole numbers, in order, for which the pivot has as few smaller elements as any input allows.

Explore in the sandbox

Experiment here, then copy a rule into the editor and test its guarantees.