Mental model
Merge sort does the easy part first (split in the middle) and the hard part last (merge). Quicksort does it the other way round: the hard part first (partition), and then nothing is left to combine.
- Pick a pivot value from the range.
- Partition: rearrange the range so that everything smaller than the pivot comes first, then the pivot, then everything else. The pivot is now exactly where it will be in the sorted array.
- Recurse on the left part and on the right part. A range of zero or one element is done.
When both recursive calls return, the whole range is sorted: the left part is sorted and smaller than the pivot, the right part is sorted and not smaller, and the pivot is between them.
This implementation
The lab and the four listings use one precise version, so every step is reproducible:
- Bounds:
sortRange(low, high)sortsitems[low..high], both inclusive. The first call issortRange(0, n − 1);low ≥ high(zero or one element) is the base case. - Pivot rule: the middle element, index
low + (high − low) / 2(rounding down, written so thatlow + highcannot overflow). It is swapped to indexhighand stays there during the partition. - Partition scheme: Lomuto. One index
jscanslow..high−1; a second indeximarks the end of the "smaller than pivot" part. - Recursion: left part first, then right part, both recursively.
The Lomuto partition
pivot = items[high] (after parking the middle element there)
i = low
for j in low .. high − 1:
if items[j] < pivot:
swap items[i], items[j]
i = i + 1
swap items[i], items[high] (the pivot moves to its final place)
return i
Invariant, true before every iteration of the loop:
low i j high
[ < pivot | ≥ pivot | unseen | pivot ]
When items[j] is smaller than the pivot, swapping it with items[i] (the first "≥ pivot"
element) and advancing i extends the left part by one. Otherwise j just moves on, which
extends the right part. When j reaches high, the unseen part is empty, and swapping the pivot
into slot i puts it between the two parts. In the lab, the tags < p and ≥ p show the two
regions growing, and the pins mark i and j.
Sometimes i = j and the swap exchanges an element with itself. That is harmless; the Swaps
metric counts it, because the code executes it.
The recursion stack
The brackets in front of the array in the lab are the active sortRange calls, outermost at the
back, innermost (bright) at the front. The text panel lists them too. Two things to notice:
- Calls on empty ranges (
low > high) happen whenever the pivot lands at the edge of its range. They return immediately but still cost a call. - The depth depends on how balanced the splits are. That is the whole story of quicksort's performance.
Cost
Each partition of m elements makes m − 1 comparisons. What matters is how the partitions nest.
Balanced splits. If the pivot always lands near the middle, every level of recursion partitions about n elements in total, and there are about log₂ n levels: Θ(n log n) comparisons and Θ(log n) stack depth. The Already sorted preset is this case for the middle pivot: 15 sorted values split into 7 and 7, then 3 and 3, then 1 and 1.
Unbalanced splits. If the pivot is always the smallest or largest value, one side is empty and the other has m − 1 elements: (n − 1) + (n − 2) + … + 1 = n(n − 1)/2 comparisons, Θ(n²), and the stack grows to n frames.
Average. For random input (or a random pivot) the expected number of comparisons is about 2n ln n ≈ 1.39 n log₂ n. That is more comparisons than merge sort, but quicksort moves fewer elements, works in place and scans memory sequentially, which is why tuned quicksorts are fast in practice.
| Measure | Best / average | Worst |
|---|---|---|
| Comparisons | Θ(n log n) | n(n − 1)/2 |
| Extra space (stack) | Θ(log n) | Θ(n) with this recursion |
| Stable | no | no |
Choosing the pivot
The pivot rule decides which inputs are slow. Every deterministic rule has some bad input; the question is whether that input is likely.
- First or last element: sorted and reversed input, which are common in practice, are the worst case. Avoid.
- Middle element (this lesson): sorted and reversed input split perfectly. Bad inputs still exist; they are just unlikely by accident. An attacker who knows the rule can construct one.
- Median of three (first, middle, last): better splits on typical data, still deterministic.
- Random pivot: no fixed input is bad; the expected cost is O(n log n) for every input. The trace would no longer be reproducible from the input alone, which is why this lab does not use it.
Lomuto's weakness: equal keys
Run the All equal preset. With every key equal, no element is strictly smaller than the pivot, so
i never moves, the pivot lands at low, and the right part has every remaining element. That is
the unbalanced case: n(n − 1)/2 comparisons and stack depth n, for an input that is already sorted.
Arrays with many duplicates come close to this.
Two standard fixes:
- Hoare's partition (the original 1962 scheme) moves two indices toward each other and stops
both on elements equal to the pivot, so runs of equal keys are split roughly in half. It also
makes fewer swaps than Lomuto. It is harder to get right: the pivot does not necessarily end up
in its final slot, and the recursion uses
[low, p]and[p + 1, high]. - Three-way partitioning (Dijkstra's "Dutch national flag") splits the range into
< pivot,= pivotand> pivotand recurses only on the outer two. All-equal input then takes one pass.
Keeping the stack small
Recursing on both sides can use Θ(n) stack in the worst case, enough to overflow on large inputs (Python's default recursion limit is about 1,000). The fix is simple: recurse on the smaller part and loop on the larger one. The smaller part is at most half the range, so the depth is at most log₂ n, whatever the pivots. The teaching version keeps both calls recursive so the lab can show the left-then-right order clearly.
What libraries do
No mainstream library ships plain quicksort; they all guard against its worst case:
- C++
std::sortmust make O(n log n) comparisons since C++11. libstdc++ and libc++ use introsort: quicksort that switches to heap sort when the recursion gets too deep (about 2 log₂ n), and insertion sort for small ranges. - C#
Array.Sort/List<T>.Sort: also an introspective sort (quicksort, heap sort fallback, insertion sort), documented as unstable. - Java
Arrays.sortfor primitives: a dual-pivot quicksort (two pivots, three parts). Object arrays use TimSort instead, because objects need a stable sort. - Python does not use quicksort at all:
list.sortis Timsort, stable and adaptive.
Not stable
Run the Not stable preset: 2a 2b 1. The middle element 2b is parked at the end as pivot,
1 is swapped to the front, and the pivot swap puts 2b at index 1 and 2a at index 2:
1 2b 2a. Partition swaps jump elements over equal ones. If you need stability, use merge sort
or your language's stable sort.
The teaching implementation
Quicksort.Sort / quicksort takes a comparison (or a key in Python) and follows the exact
rules above. The C++ version uses signed indices so that the empty range [low, low − 1] needs no
special case. Because quicksort is unstable, the shared fixture records the exact order this
implementation leaves equal keys in (all-equal 4a 4b 4c 4d becomes 4b 4c 4a 4d), and all four
languages must reproduce it; each is also compared with its built-in sort on 500 random inputs.
Common mistakes
(low + high) / 2in fixed-width integers: overflows for huge arrays. Uselow + (high − low) / 2.- Recursing on
[low, p]with Lomuto: the pivot is already placed; including it can recurse forever on a two-element range. - First-element pivot on sorted data: quadratic time and a stack overflow on large inputs.
<=in the Lomuto comparison: still correct, but now equal keys all go left and the all-equal case is just as bad, mirrored.- Assuming the library sort is quicksort and therefore unstable or quadratic: check the documented contract instead.
Worked practice
1. Partition [7, 2, 9, 4, 5] with this lesson's rules. Where does the pivot end up?
Answer
The middle index is 2, value 9; it is swapped to the end: [7, 2, 5, 4, 9]. Every other value is
smaller than 9, so each one is "swapped" with itself and i reaches 4. The final swap leaves 9 at
index 4, its sorted position. The left part [7, 2, 5, 4] holds everything else and the right
part is empty: an unbalanced split, even though the input was not sorted.
2. With the middle pivot, how deep does the stack get on 15 sorted values?
Answer
4 frames. The range sizes are 15, 7, 3 and 1: each pivot is the true median, so every split is perfect (the one-element calls are the base case at depth 4).
3. Why does random pivot selection make quicksort's worst case unlikely but not impossible?
Answer
Every run can still pick the smallest element by chance at every level, so n(n − 1)/2 comparisons remain possible. But the probability of consistently bad pivots falls off extremely fast, and no particular input triggers it: the expected cost is O(n log n) for every input.
Summary
- Quicksort partitions around a pivot, which lands in its final place, then recurses on both sides.
- Lomuto:
items[low..i) < pivot ≤ items[i..j); simple, but quadratic on many equal keys. - Balanced splits give Θ(n log n) and Θ(log n) stack; unbalanced ones give Θ(n²) and Θ(n) stack.
- The middle pivot handles sorted input; random pivots, three-way partitioning and introsort make production sorts robust.
- In place, fast in practice, not stable.