Quick Sort
Partition around a pivot (last element of each range), then recurse, the pivot lands in its final home.
Partition around a pivot (last element of each range), then recurse, the pivot lands in its final home.
step 1 / 21
What's happening
Quick sort: pick a pivot (last element here), move smaller values left of it and larger right, then recurse into both sides.
P marks the pivot (last element of the range); B marks the boundary of the “smaller” region. After partitioning, the pivot sits at its final index forever. Try sorted input to trigger the O(n²) worst case.
Understand the algorithm
What it is
Quick sort partitions the array around a pivot, smaller values left, larger right, placing the pivot at its final home, then recurses on both sides.
Why it matters
It is the most-used general-purpose sort in practice (C's qsort, C++ introsort core) because its partitioning is cache-friendly and its constants are tiny. It also teaches the biggest lesson in algorithm engineering: pivot choice turns an O(n log n) average into an O(n²) worst case.
How it works
- 1Choose a pivot (here: the last element of the range).
- 2Sweep the range, moving every value smaller than the pivot to the left region.
- 3Swap the pivot just after that region, it is now at its final sorted index.
- 4Recurse on the left and right parts; ranges of size ≤ 1 are done.
Real-world uses
- General-purpose in-memory sorting (language runtimes, database engines)
- Quickselect, the same partitioning finds the k-th smallest in O(n) average
- Situations needing in-place sorting with small constants
Strengths
- O(n log n) average with the best cache behavior of comparison sorts
- In place, O(log n) stack, no buffers
- Partitioning is a reusable primitive (quickselect, 3-way partition)
Limitations
- O(n²) worst case on adversarial/sorted input with a naive pivot
- Not stable
- Recursion depth can hit O(n) without tail-call handling or median-of-three
Go deeper
Try sorted input to see the worst case unfold with the naive pivot.