Median of Medians
Table of Contents
Given n elements from a totally ordered universe, find
kth
smallest.
- Divide and conquer,
- General problem
- Minimum:
- Maximum:
- Median: .
- Possible approaches
- compares for min or max
- compares by sorting
- compares with a binary heap. (max heap with
k
smallest)
Applications: Order statistics; find the “top k”; bottleneck paths, …
Q. Can we do it with compares?
A. Yes! Selection is easier than sorting.
Choosing the pivot element #
- Divide n elements into groups of 5 elements each (plus extra).
- Find median of each group (except extra).
- Find median of medians recursively.
- Use median-of-medians as pivot element.
MOM-SELECT(A, k):
n = |A|
if (n < 50)
return kth smallest of element of A via mergesort
Group A into ⎣n / 5⎦ groups of 5 elements each (ignore leftovers)
B = median of each group of 5
p = MOM-SELECT(B, ⎣n / 10⎦) # median of medians
(L, M, R) = PARTITION-3-WAY(A, p)
if (k ≤ |L|)
return MOM-SELECT(L, k)
else if (k > |L| + |M|)
return MOM-SELECT(R, k - |L| - |M|)
else
return p