SearchingSearching
Quickselect (k-th smallest)
Find the k-th smallest element in expected O(n) by partitioning like quicksort but recursing into only one side.
29
0
↑lo
10
1
14
2
37
3
13
4
5
5
42
6
21
7
↑hi
1/31Find the 4-th smallest element (0-based rank k=3) without fully sorting. Like quick sort, but after each partition only the side containing rank k is kept.
PivotComparing with pivotSwappedLess than pivotk-th smallestEliminated
PseudocodeLearn Quickselect →
1lo = 0, hi = n - 1, k = k - 1 # 0-based rank2while lo <= hi:3 pivot = a[hi]; i = lo4 for j in lo .. hi-1:5 if a[j] < pivot: swap(a[i], a[j]); i += 16 swap(a[i], a[hi])7 if i == k: return a[i]8 if k < i: hi = i - 19 else: lo = i + 1Variables
k3
lo0
hi7
Complexity
best O(n)
avg O(n)
worst O(n²)
space O(1)
Speed