Algorithms · Visualized
Order: Quickselect
Order Statistics
Find the k-th smallest, medians, and top-k without full sorting.
Finds the k-th smallest (or largest) element in an unsorted array without fully sorting it, using Quick Sort's partitioning step but only recursing into the single side that contains the target rank, discarding the other side entirely. Time: O(n) average, O(n²) — mitigated with random pivot selection (see Randomized Quickselect) worst; space: O(log n) — recursion stack on average.
Big-O: Quickselect O(n) average; heaps O(n log k).
Quickselect
Order StatisticsFinds the k-th smallest (or largest) element in an unsorted array without fully sorting it, using Quick Sort's partitioning step but only recursing into the single side that contains the target rank, discarding the other side entirely.
How Quickselect Works
- Pick a pivot element from the current portion of the array (first, last, middle, or random).
- Partition the array around the pivot: smaller elements to the left, larger to the right, with the pivot landing in its final sorted position.
- Compare the pivot's final index to the target rank k.
- If they match, return the pivot value — you're done.
- If k is smaller, recurse only into the left partition; if k is larger, recurse only into the right partition (adjusting k if needed for the right side's relative position).
Quickselect Worked Example
Input: {array: [7, 10, 4, 3, 20, 15], k: 3}
Looking for the 3rd smallest. Pivot=15 (last element). Partition: [7,10,4,3] left, [20] right, pivot lands at index4 (5th smallest). k=3 < 4, recurse left into [7,10,4,3]. Pivot=3 (last). Partition: [] left, [7,10,4] right, pivot lands at index0 (1st smallest overall in this sub-array). k=3, need position2 within this subarray (0-indexed) → recurse right into [7,10,4]. Eventually finds the 3rd smallest element: 7.
import random
def quickselect(arr, k):
# kth smallest, 0-indexed
lo, hi = 0, len(arr) - 1
while lo <= hi:
pivot = random.choice(arr[lo:hi + 1])
less, equal, greater = [], [], []
for v in arr[lo:hi + 1]:
if v < pivot: less.append(v)
elif v == pivot: equal.append(v)
else: greater.append(v)
if k < len(less):
arr = less; hi = len(arr) - 1; lo = 0
elif k < len(less) + len(equal):
return pivot
else:
k -= len(less) + len(equal)
arr = greater; hi = len(arr) - 1; lo = 0Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Quickselect Time & Space Complexity
When to Use Quickselect
- Finding medians, percentiles, or the k-th best/worst item without a full sort — used internally by many statistics and data-processing libraries.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.