Algorithms · Selection
Quickselect.
Watch the explainer
You want the 5th-smallest value — or the median. Sorting the whole array gets it, but that’s O(n log n) of work for a single answer. Quickselect borrows quicksort’s partition and throws away half the array at every step: partition around a pivot, ask which side your target rank lives in, and recurse into only that one. Average linear time, no full sort.
Average O(n) · worst O(n²) · in-place · selection
rank kThe index the answer would sit at if the array were sorted (0-based).
partitionRearrange around a pivot so smaller-left, larger-right; the pivot lands at its final spot.
pivot index pWhere the pivot ends up. Compare it to k to pick a side.
recurse one sideDiscard the half that can’t contain rank k. This is the whole speedup.
quickselect.js — find rank k, keep one side
Ready
We’re hunting rank k = 4 — the 5th-smallest value. Each Step partitions the active range around a pivot (the last element), lands it at index p, then keeps only the side that contains k.
How it works
Quickselect is quicksort that stops caring about the half it doesn’t need. After one partition, the pivot sits at its true sorted position p. That single fact tells you everything: if p == k the pivot is the answer; if k < p the answer is somewhere on the left; if k > p, on the right. Whichever side, you drop the other entirely.
1Partition the active range
Pick a pivot (here the last element), sweep once moving smaller values left, and place the pivot at the boundary — its final index p.
2Compare p to k
p == k → found it. k < p → recurse left. k > p → recurse right.
3Discard the other half
Only one side can hold rank k, so the other is gone — the search range shrinks, usually by about half.
✓Repeat until p == k
Each round works on a smaller range: n + n/2 + n/4 + … ≈ 2n. That’s why the average is linear.
vs full sort
skips the log n
The code
# kth-smallest (0-indexed rank), average O(n)
def quickselect(a, k):
lo, hi = 0, len(a) - 1
while lo < hi:
p = partition(a, lo, hi) # pivot lands at p
if p == k: return a[p]
elif p < k: lo = p + 1 # answer is on the right
else: hi = p - 1 # answer is on the left
return a[lo]
def partition(a, lo, hi):
pivot, i = a[hi], lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
return i
Randomize the pivot (swap a random element to hi before partitioning) to make the O(n²) worst case astronomically unlikely. For a hard guarantee, the median-of-medians pivot rule gives worst-case O(n) — at a larger constant that usually isn’t worth it in practice.
Quick check
1. Why is quickselect average O(n) while quicksort is O(n log n)?
Right — quicksort sorts both halves (adding the log n factor); quickselect throws one half away each time, collapsing the geometric series to linear.
2. After a partition, the pivot index is p. When do you recurse right?
The pivot is now at its true sorted spot p. If your target k is greater than p, the answer must be among the larger elements to the right.
FAQ
What is quickselect used for?
Finding medians, percentiles, and top-k or bottom-k elements without fully sorting. It’s the engine behind fast "kth largest" and library selection routines like C++'s nth_element.
How do I find the median with it?
The median is just rank n/2 (for odd n). Run quickselect with k = n/2. For even n, take the two middle ranks and average them.
What’s the worst case, and how do I avoid it?
O(n²) on adversarial inputs with consistently bad pivots. Randomizing the pivot makes it practically impossible; median-of-medians guarantees O(n) worst case with a bigger constant.
Does it fully sort the array?
No — it only rearranges enough to place rank k correctly. The array ends up partially ordered around the pivots it chose, which is exactly the point: it does the minimum work for one answer.
The picture: three partitions, one side kept each time
Each row is the array right after a partition. The highlighted box is the pivot at its final sorted index; shaded boxes are discarded for good; plain boxes are what the next round still has to look at. Eight elements, then six, then three, then done.
Worked example, step by step
Find the 5th-smallest element of A = [3, 1, 4, 1, 5, 9, 2, 6], so k = 4 counting from 0. The pivot is always the last element of the active range [lo, hi], which makes the run reproducible. Partition: sweep once, moving values smaller than the pivot to the front, then place the pivot after them.
Only 3 partitions ran, over ranges of 8, 6 and 3 elements: 7 + 5 + 2 = 14 comparisons, against roughly 8 × log₂ 8 = 24 for sorting the array first. The final array is [1, 1, 2, 3, 4, 5, 6, 9], which happens to be sorted, but that is luck. The guarantee is only that index 4 holds the right value, with everything smaller before it and everything larger after. Ranges shrank 8, 6, 3, 1: the geometric shrinking is what makes the total work linear. Note the duplicate 1s: they ended up at indices 0 and 1, so the 5th-smallest is 4, but the 2nd-smallest would be 1 as well, because rank counts positions, not distinct values.
Complexity and trade-offs
Measured on code: with a last-element pivot, the already sorted array of 1,000 values and k = 0 costs 499,500 comparisons, exactly n(n−1)/2. A shuffled 1,000-element array (Python random.Random(1)) with k = 500 costs 3,670. A random pivot makes the first case as unlikely as the second is typical. Practical libraries use introselect: start with quickselect and switch to a guaranteed method if recursion gets too deep, so they get the average speed and a worst-case bound together.
Common mistakes
- Mixing 0-based and 1-based k
The index k = 4 is the 5th-smallest. On this page’s array the 4th-smallest is 3 and the 5th is 4; asking for “the 4th” with k = 4 returns 4. For the kth largest, use k = n − k on the sorted order.
- A fixed pivot on sorted input
Last-element or first-element pivots on sorted data discard one element per round. A sorted array of 1,000 with k = 0 takes 499,500 comparisons instead of a few thousand. Swap a random element into the pivot slot before partitioning.
- Many equal values with a strict < partition
In [5, 5, 5, 5, 5] nothing is smaller than the pivot, so every partition leaves the pivot at lo and shrinks the range by one: 10 comparisons for 5 elements, quadratic in general. A three-way partition (less, equal, greater) finishes this in one pass.
- Setting hi = p instead of p − 1
The pivot is already placed and ruled out, so the next range should exclude it. On [3, 1, 4, 1, 5, 9, 2, 6] with k = 4, hi = 6 after round 1 produces the same partition again, forever.
- Forgetting that the input is reordered
Quickselect permutes the array in place. A caller that still expects the original order, or that holds an index into it, now sees shuffled data. Copy first if the order matters.
Where this shows up
- Standard libraries
C++’s std::nth_element and NumPy’s np.partition are selection routines of this family (NumPy’s uses introselect). np.median relies on partitioning rather than a full sort.
- Percentiles and medians
A p95 latency over a window of samples is the element at rank 0.95 × n. When you need one rank rather than the whole distribution, selecting is cheaper than sorting.
- Top-k problems
“Kth Largest Element in an Array” is the textbook case. After the selection runs, the k elements to one side of the pivot are the top k, unordered, which is all many problems need.
- Building k-d trees
A balanced k-d tree splits at the median of one coordinate per level. Selecting that median with nth_element rather than sorting keeps construction near O(n log n) instead of O(n log² n).
SOLVE IT YOURSELF
Solve it: the kth smallest, without sorting
Sorting to find one element does far more work than you need. Partition, throw away the half that cannot contain the answer, repeat. Write it in Python or TypeScript, running for real in your browser.
YOUR TASK
Implement kth_smallest(nums, k): return the k-th smallest value (k is 1-based, so k=1 is the minimum). Do not sort the whole list — partition and recurse into one side only.
HINTS — 5 IDEAS
- Convert
k to a 0-based target index once, up front: target = k - 1.
- Partition around a pivot so everything smaller sits left of it. The pivot then lands at its final sorted index
p.
- If
p == target you are done — that slot already holds the answer.
- Otherwise recurse into one side only:
target < p means search left, else search right. Discarding the other half is the whole trick.
- Average O(n) because the work halves each round (n + n/2 + n/4 … = 2n), worst case O(n²) on an unlucky pivot.
CPython · WebAssembly
✓ Solved