Median of Medians Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Median of Medians runs in O(n) time and O(n) space, in Python as in every other language.
- ✓CPython ships no nth_element. statistics.median_low(g) (import statistics) gives you an ELEMENT of the group rather than an average, which is what a pivot must be; for groups of five sorted(g)[2] is cheaper.
- ✓Reviewers insist the recursion carries (lo, hi) index bounds into ONE list and never a slice, because a[lo:hi] copies.
- ✓The Python trap: statistics.median averages the two middle values on an even-length group, so it can return a number that is NOT in the array -- and for ints it returns a float.
- ✓Every comparison is a PyObject_RichCompare dispatch through the interpreter loop, so the constant factor is roughly 50-100x C.
What Median of Medians actually is
Median of Medians in Python: what you actually reach for
Python implementation
def _ins(a, lo, hi):
for i in range(lo + 1, hi):
v = a[i]; j = i - 1
while j >= lo and a[j] > v:
a[j + 1] = a[j]; j -= 1
a[j + 1] = v
def _pivot(a, lo, hi):
n = hi - lo
if n <= 5:
_ins(a, lo, hi)
return lo + n // 2
m = lo
for g in range(lo, hi, 5):
e = min(g + 5, hi)
_ins(a, g, e)
mid = g + (e - g) // 2
a[m], a[mid] = a[mid], a[m]
m += 1
return _select(a, lo, m, lo + (m - lo) // 2)
def _select(a, lo, hi, k):
while hi - lo > 1:
p = _pivot(a, lo, hi)
a[lo], a[p] = a[p], a[lo]
pv = a[lo]; i = lo
for j in range(lo + 1, hi):
if a[j] < pv:
i += 1
a[i], a[j] = a[j], a[i]
a[lo], a[i] = a[i], a[lo]
if k == i:
return k
if k < i:
hi = i
else:
lo = i + 1
return k
def select_kth(a, k):
return a[_select(a, 0, len(a), k)]Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Median of Medians?
CPython ships no nth_element. statistics.median_low(g) (import statistics) gives you an ELEMENT of the group rather than an average, which is what a pivot must be; for groups of five sorted(g)[2] is cheaper. heapq.nsmallest(k, it) covers tiny k in O(n log k). numpy.partition / numpy.argpartition (import numpy) do the real job in C using introselect: a median-of-3 quickselect that falls back to median-of-medians-of-5 once the recursion budget is spent, so the worst case is O(n), not merely expected O(n). Write BFPRT yourself when you cannot take a NumPy dependency, when the data is not a dense numeric array, or to teach it -- not because NumPy's bound is weaker.
What is the most common Python mistake when implementing Median of Medians?
statistics.median averages the two middle values on an even-length group, so it can return a number that is NOT in the array -- and for ints it returns a float. Use it as your pivot and two things break, both of them Python-specific. For large ints the averaging itself blows up before any comparison happens: statistics.median([10**400, 10**400 + 2]) raises OverflowError: integer division result too large for a float (verified). Below that ceiling you get a float pivot that is exact-compared against your ints -- CPython 3 compares int against float exactly, so 2**53 + 1 == float(2**53) is correctly False -- so the mixed comparison is the one thing that does NOT lie. The damage is the pivot itself: it is a value that is not in the array, so you can no longer locate its final index by identity and 'return a[k]' has nothing to anchor to. Use statistics.median_low, or index the sorted group.
How does Median of Medians actually perform in Python?
Every comparison is a PyObject_RichCompare dispatch through the interpreter loop, so the constant factor is roughly 50-100x C. list.sort() (Timsort, C-level compares on the whole array) beats a pure-Python O(n) BFPRT at every size you will ever run: measured 9.1x faster at 10^4, 7.3x at 10^5, 6.1x at 10^6. The interpreter constant is so large that the O(n) vs O(n log n) gap closes only as log n, which never happens in practice -- so pure-Python BFPRT is for the worst-case GUARANTEE, never for speed. When you want speed, use list.sort() below ~10^5 and numpy.partition above it. The 5-element group sorts dominate: prefer an inlined insertion loop over calling sorted() n/5 times, which allocates a new list each call. Recursion depth is O(log n), so sys.setrecursionlimit is not the issue -- slice copies are. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.