Sub topic 1
What It Means to Find the k-th Smallest Element
Prerequisites
This chapter assumes you can read Python functions, loops, and list comprehensions. It also assumes you know zero-based indexing, basic Big-O notation, and recursion. Knowing quicksort helps but is not required.
The Selection Problem
The selection problem asks for the element that would sit at position k if the list were sorted. That element is called the k-th order statistic. The minimum, the maximum, and the median are all special cases.
Be careful about how k is counted. In this tutorial k is zero-based, so k = 0 means the smallest element. Many textbooks count from one, where the "1st smallest" is the minimum. Mixing up the two conventions is the most common off-by-one bug in selection code.
| Goal | Zero-based k | One-based k |
|---|---|---|
| Minimum | 0 | 1 |
| Median of 7 items | 3 | 4 |
| Maximum of n items | n - 1 | n |
You could sort the list and index into it, which costs O(n log n). Quickselect avoids most of that work.
Partitioning Around a Pivot
Partitioning picks one element, the pivot, and splits the input into three groups: elements less than the pivot, elements equal to it, and elements greater than it. After the split you know the pivot's rank without sorting anything. If lows has 4 elements, every copy of the pivot occupies sorted positions starting at 4.
Quickselect: Recursing Into Only One Side
Quicksort recurses into both groups. Quickselect compares k with the group sizes and recurses into only the group that must contain the answer:
- If k < len(lows), the answer is in
lows. - If k falls inside the run of pivot copies, the pivot is the answer.
- Otherwise, search
highswith k shifted down by the number of elements skipped.
import random
def quickselect_simple(items, k):
"""Return the k-th smallest element (0-based) of a non-empty list."""
pivot = random.choice(items)
lows = [x for x in items if x < pivot]
pivots = [x for x in items if x == pivot]
highs = [x for x in items if x > pivot]
if k < len(lows):
return quickselect_simple(lows, k)
if k < len(lows) + len(pivots):
return pivot
return quickselect_simple(highs, k - len(lows) - len(pivots))
print(quickselect_simple([9, 1, 8, 2, 7, 3], 2)) # 3Exercise
A colleague wants the 3rd smallest element using one-based counting. What k should they pass to quickselect_simple, and what does it return for [9, 1, 8, 2, 7, 3]?
Show answer
Pass k = 2, because zero-based k is the one-based rank minus 1. The result is 3, since the sorted list is [1, 2, 3, 7, 8, 9].