Divide & conquerAnimated
Quick Select
Quick sort that only recurses into the side holding the k-th item.
Time
O(n) avg, O(n²) worst
Extra space
O(1)
Use it for
k-th smallest and medians.
How it works
- To find the k-th smallest you do not need the whole array sorted.
- Partition around a pivot (the last element): smaller items go left, bigger go right, and the pivot lands in its final sorted position p.
- If p is the position you want (k − 1), you are done. If k − 1 is smaller, search only the left side; if larger, only the right side.
- Throwing away half each time gives O(n) on average (O(n²) worst case, avoided by random pivots).
Watch it run
Loading animation…