Data Structures · Sorting

Quick Sort

🔢 The array a[] (current range / settled pivots)

settled pivot (final position)current range [lo, hi]pivotj scanning / i target
result

🧾 Partition record

💬 Current step

💻 The algorithm (courseware-style C++)

Yellow = the line being executed. One partition settles exactly one position (the pivot), then both halves are recursed into.

📄 Key points

1Take the range's last element as the pivot
2j scans; values smaller than the pivot move to i
3Finally swap(a[i], a[hi]) → the pivot is settled for good
4Recurse into both halves; average O(n log n), worst case (sorted input) O(n²)
Why is it fast? A partition costs one scan of the range, yet the pivot splits it in two, so the recursion is only log n levels deep → average O(n log n) with a very small constant factor (just comparisons and swaps, no extra array), which is why it is usually the fastest in practice.
Worst case: when every pivot is the largest or smallest value the range shrinks by one element each time and it degrades to O(n²). A fixed last-element pivot on sorted input is the classic example (run 2 on this page); the fix is a random or median-of-three pivot.
Space: the recursion stack, O(log n) (worst O(n)); stability: the long-distance swaps skip equal values → not stable.
Optimisation: finish small ranges (length < ~10) with insertion sort to avoid a pile of recursive calls.
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result