Sub topic 1
What It Means to Find the k-th Smallest Element
Many everyday questions come down to finding one element by its rank. What was the median response time? Who has the 10th highest score? What value is greater than 95% of the measurements? Each of these asks for the element that would sit at a particular position if the data were sorted. This chapter defines that problem precisely, fixes the indexing conventions used in the rest of the tutorial, and builds a slow but trustworthy reference implementation that later chapters can be tested against.
Prerequisites
This chapter assumes you are comfortable with the following:
- Basic Python syntax: functions, loops, list comprehensions, and raising exceptions.
- Arrays (Python lists) and zero-based indexing, where the first element is at index 0.
- Big-O notation, including what O(n), O(n log n), and O(n^2) mean for growth.
- Recursion. This chapter uses none, but later chapters use it heavily.
Knowing quicksort helps but is not required. Partitioning, which is the main building block of quickselect, gets its own chapter next.
The Selection Problem
The selection problem works like this: given a collection of n comparable elements and an integer k, return the element that would be at position k if the collection were sorted in ascending order.
That element is called the k-th order statistic. Some order statistics have common names:
- The minimum is the smallest element.
- The maximum is the largest element.
- The median is the middle element.
- A percentile or quantile is the element at a given fraction of the way through the sorted order.
Selection asks for exactly one rank. It does not ask you to sort everything, and that difference is what makes faster algorithms possible. Sorting fixes the position of all n elements. Selection only needs to fix one.
Take the list used throughout this tutorial:
data = [9, 1, 8, 2, 7, 3]
print(sorted(data)) # [1, 2, 3, 7, 8, 9]With zero-based indexing, the order statistic at k = 0 is 1, at k = 2 is 3, and at k = 5 is 9.
Zero-Based Versus One-Based k
The most common source of bugs in selection code is not the algorithm. It is disagreement about what k means.
Textbooks and mathematical writing usually count ranks from one. "The 1st smallest" is the minimum, and "the 3rd smallest" is the element at index 2 of the sorted list. Code usually counts from zero, because k is used directly as an array index.
This tutorial uses zero-based k everywhere unless a sentence says otherwise. select(items, k) returns sorted(items)[k]. That matches Python list indexing, C++ std::nth_element, and numpy.partition, which are all covered in the final chapter.
The table below lists the usual queries in both conventions for a collection of n elements.
| Query | Zero-based k | One-based rank |
|---|---|---|
| Minimum | 0 | 1 |
| Maximum | n - 1 | n |
| Lower median | (n - 1) // 2 | (n + 1) // 2 |
| Upper median | n // 2 | n // 2 + 1 |
| j-th largest (j one-based) | n - j | n - j + 1 |
| j-th largest (j zero-based) | n - 1 - j | n - j |
When n is odd, the lower and upper medians are the same element. When n is even, they are the two middle elements, and you have to pick one or combine them.
The diagram below shows that workflow. Every question gets translated into a single zero-based index, the index gets validated, and only then does selection run.
Duplicates: Ranks Count Every Copy
When the input contains repeated values, "the k-th smallest" can mean two different things:
- With multiplicity. Every copy occupies its own position in the sorted order. This is the standard definition, and the one every algorithm in this tutorial uses.
- Among distinct values. Duplicates are removed first, and then you take the k-th smallest unique value.
The two give different answers:
data = [4, 1, 4, 2, 4]
with_multiplicity = sorted(data) # [1, 2, 4, 4, 4]
distinct = sorted(set(data)) # [1, 2, 4]
print(with_multiplicity[2], with_multiplicity[4]) # 4 4
print(distinct[2]) # 4
# distinct[3] would raise IndexError: only 3 distinct values existWith multiplicity, positions 2, 3, and 4 all hold the value 4, so selection returns 4 for any of those k. This matters for two reasons:
- Selection returns a value, not an identity. If you need to know which record had that value, select over (key, record) pairs or select indices, and accept that ties make the answer non-unique.
- Inputs with many equal values are a known performance hazard for simple quickselect implementations. A later chapter on three-way partitioning deals with it. For now, note that duplicates are legal input and the definition handles them without special cases.
If you really need the k-th distinct value, deduplicate first (set(data) in O(n) expected time), then run ordinary selection on the result.
A Reference Implementation
The simplest correct solution is to sort and index. It runs in O(n log n) time, which is fast enough for most real workloads. It is also obviously correct, which makes it the ideal oracle: a trusted implementation that faster code is tested against.
def kth_smallest_reference(items, k):
"""Return the k-th smallest element (0-based k) of items.
Duplicates count with multiplicity. Does not modify items.
Runs in O(n log n) time and O(n) extra space.
"""
n = len(items)
if not 0 <= k < n:
raise IndexError(f"k={k} out of range for {n} items")
return sorted(items)[k]
def kth_largest_reference(items, j):
"""Return the j-th largest element (0-based j: j=0 is the maximum)."""
return kth_smallest_reference(items, len(items) - 1 - j)
def lower_median(items):
return kth_smallest_reference(items, (len(items) - 1) // 2)
def upper_median(items):
return kth_smallest_reference(items, len(items) // 2)
def mean_median(items):
"""The statistician's median: the average of the two middle values when n is even."""
return (lower_median(items) + upper_median(items)) / 2
data = [9, 1, 8, 2, 7, 3]
print(kth_smallest_reference(data, 2)) # 3
print(kth_largest_reference(data, 0)) # 9
print(lower_median(data)) # 3
print(upper_median(data)) # 7
print(mean_median(data)) # 5.0
print(data) # [9, 1, 8, 2, 7, 3] (unchanged)A few design choices here carry through the rest of the tutorial.
Validation is explicit. Python lists accept negative indices, so sorted(items)[-1] quietly returns the maximum. That is convenient, but in a selection routine a negative k almost always means an upstream arithmetic mistake, such as computing n - j with j too large. Rejecting it early turns a silent wrong answer into a visible error. An empty input fails the same check, because no k satisfies 0 <= k < 0.
The input is not modified. sorted returns a new list. The fast in-place algorithms later in the tutorial will reorder their input. That is a real behavioral difference, and callers who need the original order must pass a copy.
mean_median is a different operation. Averaging the two middle values requires numeric elements, and it can return a value that is not in the input at all (5.0 above). Selection always returns an element of the input, so it works for any type that supports <, including strings and tuples.
Using the oracle for testing
When you write quickselect in the coming chapters, a randomized comparison against the oracle catches most bugs within a few thousand trials:
import random
def kth_smallest_reference(items, k):
if not 0 <= k < len(items):
raise IndexError("k out of range")
return sorted(items)[k]
def check(select_fn, trials=2000):
for _ in range(trials):
n = random.randint(1, 30)
# A small value range forces many duplicates.
items = [random.randint(0, 5) for _ in range(n)]
k = random.randrange(n)
expected = kth_smallest_reference(items, k)
got = select_fn(list(items), k) # pass a copy: select_fn may mutate
assert got == expected, (items, k, got, expected)
print("all trials passed")
# Sanity check: the oracle agrees with itself.
check(kth_smallest_reference)The small value range (0 to 5) is deliberate. Random inputs drawn from a wide range almost never repeat, so they never exercise the duplicate-handling paths where partitioning bugs tend to hide. Also test n = 1, k = 0, and k = n - 1 on purpose, since the boundaries are where off-by-one errors show up.
How Fast Can Selection Be?
Sorting gives O(n log n). Can we do better, and what is the floor?
Every element must be examined. Suppose an algorithm returns an answer without ever looking at some element x. An adversary could then change x to a value that moves it across the answer's position in the sorted order, which changes the correct answer, and the algorithm would not notice. So any correct selection algorithm needs Ω(n) time. Selection can never beat linear time.
The minimum and maximum hit that floor easily. One pass with a running best uses exactly n - 1 comparisons, and that is optimal for comparison-based algorithms. Every element except the true minimum has to lose at least one comparison, otherwise it could still be the minimum.
def minimum(items):
if not items:
raise ValueError("empty input")
best = items[0]
for x in items[1:]: # n - 1 comparisons
if x < best:
best = x
return best
print(minimum([9, 1, 8, 2, 7, 3])) # 1The same trick extends to small k by keeping the k smallest seen so far, but the cost grows with k. A sorted buffer of size k costs O(nk), and a heap costs O(n log k), which a later chapter compares in detail. For k near n/2, which is the median and usually the case people care about most, both are no better than sorting.
The open question is whether any rank, including the median, can be found in O(n) time. It can:
- Quickselect finds it in expected O(n) time by partitioning around a pivot and continuing into only the side that contains position k.
- Median of medians guarantees O(n) even in the worst case, at the cost of larger constant factors.
The rest of this tutorial builds both, starting with partitioning in the next chapter.
What a Selection Result Looks Like
Fast selection algorithms do more than return a value. Because they work by partitioning, they usually leave the array in a useful state. After selecting position k in place:
a[k]holds the k-th smallest element.- Every element before index k is less than or equal to
a[k]. - Every element after index k is greater than or equal to
a[k]. - Within each side, the order is arbitrary.
That state is often what you actually want. To get the 10 smallest elements in any order, select k = 9 and take a[:10]. You get them without paying to sort them. Library routines such as std::nth_element promise exactly this arrangement, as the final chapter shows.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Passing a one-based rank as zero-based k | Answer is one position too high, and k = n raises an error | Convert at the API boundary: `k = rank - 1` |
| Computing the j-th largest as `n - j` with zero-based j | Off by one, and j = 0 indexes past the end | Use `n - 1 - j` for zero-based j |
| Relying on Python's negative indexing | Wrong answer instead of an error | Validate `0 <= k < n` explicitly |
| Deduplicating when the spec means multiplicity | Wrong ranks whenever duplicates exist | Keep duplicates unless distinct values are explicitly required |
| Assuming the input is unchanged | Caller's data is reordered by an in-place routine | Document the mutation or pass a copy |
| Using the mean median where an element is required | Result is a float that is not in the data | Pick the lower or upper median explicitly |
Exercise
A list has n = 8 elements. Give the zero-based k for (a) the minimum, (b) the maximum, (c) the lower median, (d) the upper median, and (e) the 3rd largest element, where "3rd largest" is one-based so the maximum is the 1st largest.
Show answer
(a) 0. (b) n - 1 = 7. (c) (n - 1) // 2 = 3. (d) n // 2 = 4. (e) n - j with j = 3, so k = 5. Check: in sorted positions 0..7, the 1st largest is at 7, the 2nd at 6, and the 3rd at 5.
Exercise
For data = [6, 3, 6, 1, 6, 2], what does kthsmallestreference(data, 3) return, and what is the 3rd smallest distinct value (zero-based index 3 into the sorted distinct values)?
Show answer
sorted(data) is [1, 2, 3, 6, 6, 6], so k = 3 returns 6. The sorted distinct values are [1, 2, 3, 6], so index 3 is also 6 here. At k = 4, the multiplicity version still returns 6, while the distinct version raises IndexError because there are only 4 distinct values.
Exercise
Explain why no comparison-based algorithm can find the median of n elements without examining all n of them, and why this does not rule out an O(n) algorithm.
Show answer
If some element x is never examined, an adversary can set x to a value just below or just above the reported answer and change which element sits at the median position, so the reported answer would be wrong for that input. Every element must therefore be read at least once, giving an Ω(n) lower bound. That bound is linear, so it is consistent with O(n) algorithms. It only rules out sublinear ones. Quickselect (expected) and median of medians (worst case) both reach it.