Quicksort sorts in place by splitting the array around one element, the pivot. On 48 numbers that are already sorted, a last-element pivot costs 1,128 comparisons. A random pivot costs about 245.
Pick an input and a pivot rule, then press Sort. Watch the bars and the comparison count. Then we build it piece by piece: the partition, the recursion, the cost of a bad split, the random fix, and the library variants.
You need arrays and recursion (a function that calls itself), and a little Python. We build the rest from zero.
Based on Chapter 7 of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. It follows Chapter 6, Heapsort. The explanations, toys and devices are our own.
The sort on this page measures every count live (Lomuto partition, one comparison per element scanned). The random pivot uses a seeded generator, so a rerun can differ by a few comparisons.
Chapter 0
See why we want a fast sort with no extra array, and meet the one move that gives it
You must sort one million numbers on a device with little memory. Merge sort takes about n log n steps, but it needs a second array of one million slots to merge into. Heapsort needs no second array, but it jumps around memory and runs slower in practice.
Quicksort keeps the array where it is. Pick one element, the pivot. Move every element that is at or below the pivot to its left, and every larger element to its right. This one pass is the partition.
Look at what the pass does. The pivot now sits exactly where it will sit in the sorted array. Its two sides are separate problems, so you sort each side the same way. There is nothing to merge afterwards.
Slide to choose which bar is the pivot. The bars split into a low side and a high side, and the pivot lands in its sorted place.
Twelve made-up values from 1 to 12. The device keeps the original order inside each side; a real partition may shuffle the order inside a side.
A worked number: the values are 1 to 12 and the pivot is 5. Four values are smaller, so the pivot lands at index 4, counting from 0. The split is 4 on the left and 7 on the right. A pivot near the middle gives two halves; the smallest or largest value gives a split of 0 and 11.
The failure. Symptom: the sort is fast on test data but crawls on real data that arrives in order. Measure: count comparisons and compare with n times log2 n. Fix: choose the pivot better (Chapter 4).
Chapter 1
Step through the Lomuto partition and see the invariant that makes it correct
CLRS uses the Lomuto partition. It takes the last element as the pivot. It walks a scanner j from left to right. It keeps a boundary i: everything at or left of i is at or below the pivot.
Press Step. Teal is the low side, purple the high side, grey not yet seen, warm the pivot. Try the sorted and all-equal inputs too.
The first input is the example CLRS traces in Figure 7.1. The counts are the device's own.
The worked number, on the CLRS array 2, 8, 7, 1, 3, 5, 6, 4 with pivot 4. The scanner sees 2, 1 and 3 at or below 4, so i grows three times. The final swap puts 4 at index 3. The array becomes 2, 1, 3, 4, 7, 5, 6, 8. That took 7 comparisons and 4 swaps, counting the final one.
A loop invariant is a fact that holds before every step of a loop. Here it has three parts:
At the start both sides are empty, so it holds. Each step keeps it. When j reaches hi, nothing is unseen, and the final swap puts the pivot between the sides.
The failure. Symptom: a sorted array of 8 elements comes out with the pivot at the far right every time. Measure: print q after each partition; it equals hi. Fix: nothing is wrong with partition. The split is 7 to 0, and Chapter 3 shows what that costs.
Chapter 2
Wrap the partition in three lines of recursion and count every comparison it makes
Partition places one element. Quicksort calls partition, then calls itself on the left side and on the right side. A side with 0 or 1 elements is already sorted, so the call returns at once. That is the base case.
pythondef quicksort(A, lo, hi): if lo < hi: # 2 or more elements q = lomuto_partition(A, lo, hi) # pivot lands at q quicksort(A, lo, q - 1) # left of the pivot quicksort(A, q + 1, hi) # right of the pivot
Compare it with merge sort. Merge sort splits for free and does its work after the recursion, in the merge. Quicksort does its work before the recursion, in the partition, and has nothing to combine.
Each Step runs one partition call. Blue is the active range, warm the pivot, green a placed element. The tree below shows each call under its parent.
Same CLRS array as Chapter 1. The device counts one comparison per element that Lomuto scans.
The worked count. Five calls do a partition, on ranges of 8, 3, 2, 4 and 3 elements. Each partition of m elements makes m − 1 comparisons. So the total is 7 + 2 + 1 + 3 + 2 = 15 comparisons. Every element is a pivot once or ends in a base case of size 1.
Use induction on the size. A range of 0 or 1 elements needs no work. For a larger range, partition puts every smaller-or-equal element left of q and every larger one right of q. Both sides are smaller than the range, so by induction the two calls sort them. Sorted left, then the pivot, then sorted right, is a sorted range.
The failure. Symptom: the sort never returns. Measure: print lo and hi at each call; the same pair repeats. Fix: recurse on q − 1 and q + 1, never on q. The pivot must leave both sides, or a side can stay the same size forever.
Chapter 3
Turn the split ratio and watch the call tree go from a bushy tree to a long chain
Feed a sorted array to quicksort with a last-element pivot. The pivot is always the largest value. Each partition removes only the pivot and leaves everything else on one side. How many comparisons is that in total?
Call the number of elements n. The first partition makes n − 1 comparisons, the next n − 2, and so on down to 1. Call the total Cworst(n).
C-worst of n equals n minus 1, plus n minus 2, down to 1. That is n times n minus 1, over 2.
Each level scans every element that is left, minus the pivot. Add those scans for all n − 1 levels. The total grows like n squared.
n = 5: 4 + 3 + 2 + 1 = 10 = 5 × 4 / 2. For n = 1,000,000 it is 499,999,500,000 comparisons.
Now the best case: every pivot is the median, so each side gets half. Call the cost of sorting n elements T(n).
T of n equals two times T of n over 2, plus n.
Each level of the tree scans all n elements once, split across its calls. Halving reaches size 1 after log2 n levels. So T(n) is about n times log2 n.
n = 1,000: about 1,000 × 10 = 10,000. The exact count with perfect medians is 7,987, because each scan is m − 1 and the pivot leaves each level.
Each row is one level of the call tree for 1,000 elements; each block is one call. Slide toward the right to make every split more lopsided. The far right is the worst case.
Every call on this page splits by the same ratio, which a real sort never does. The counts are exact for that toy rule.
Drag to 90%. A 9 to 1 split looks terrible, yet the tree is only 49 levels deep and costs 16,967 comparisons. Any fixed fraction keeps the depth near log n. Only a split that peels off a constant number of elements, like 999 to 0, gives the chain.
Chapter 4
Swap a random element into the pivot slot and see the sorted-input disaster disappear
The worst case comes from a fixed rule meeting a matching input. "Always the last element" meets "already sorted". Anyone who knows your rule can build that input. So take the rule away. Before each partition, pick a random index in the range and swap that element to the end.
pythonimport random def randomized_partition(A, lo, hi): r = random.randint(lo, hi) # any index in [lo, hi], inclusive A[r], A[hi] = A[hi], A[r] # the random element becomes the pivot return lomuto_partition(A, lo, hi)
Now the input cannot pick the pivots. A random pivot lands in the middle half of the values with probability 1/2. Then the larger side holds at most 3/4 of the elements. About every second level is that good, so the depth stays near log n.
The red mark is the last-element pivot. Each teal dot is one run with a random pivot. The axis is a log scale from n to n squared over 2.
Every run is a real randomized quicksort on 0, 1, …, n − 1 in this page. The expected value line comes from Chapter 5's formula.
The worked number at n = 1,024. The last-element pivot makes 523,776 comparisons. Random pivots average about 11,298. That is 46 times fewer, on the same input.
Two words matter here. Average case means the input is random and the algorithm is fixed. Expected time means the input is fixed, even the worst one, and the algorithm flips the coins. Randomized quicksort promises the second. It is a Las Vegas algorithm: the answer is always correct; only the time varies.
The failure. Symptom: 0.5 s on random data, minutes on sorted data. Measure: log the pivot index; it is always hi. Fix: one line, the random swap above.
Chapter 5
Ask when two values ever meet, and add up the chances to get 2n ln n
Tracing every random pivot is hopeless. CLRS counts a different way. Quicksort compares two values only when one of them is the pivot. After that partition, nothing compares the pivot again. So each pair meets at most once.
Name the values by their sorted rank: z1 is the smallest, zn the largest. Take two ranks, i below j. Look at the values from zi to zj. If a value strictly between them becomes a pivot first, it sends zi left and zj right, and they never meet. They meet only if zi or zj is the first pivot picked from that group.
The probability that z-i meets z-j equals 2 over j minus i plus 1.
Count the values from z-i to z-j. Two of them make the pair meet. Divide 2 by that count.
Ranks 2 and 6: the group is z2 to z6, which is 5 values. The chance is 2/5 = 0.4. Neighbours, like ranks 3 and 4, give 2/2 = 1: they always meet.
Now add. Let X be the total number of comparisons. Each pair adds 1 when it meets, so the expected total is the sum of every pair's chance. This is linearity of expectation: the average of a sum is the sum of the averages, even when the parts depend on each other.
E of X equals the sum over i less than j of 2 over j minus i plus 1. That is about 2 n ln n.
Group the pairs by their gap k = j − i. There are n − k pairs with gap k, and each meets with chance 2/(k + 1). Add the groups. The fractions 1/2, 1/3, 1/4 and on add up like ln n, so the total is about 2n ln n.
n = 8. Gap 1 gives 7 × 1 = 7. Gap 2 gives 6 × 2/3 = 4. Gaps 3 to 7 give 2.5, 1.6, 1, 0.57 and 0.25. E[X] = 16.92 comparisons.
Cell (i, j) is the chance that ranks i and j meet. Tap a cell to read it. Change n and watch the sum.
The cells are exact. The exact sum is 2(n + 1)Hn − 4n, where Hn = 1 + 1/2 + … + 1/n.
At n = 1,000,000 the exact expectation is about 24.8 million comparisons. The rough form 2n ln n gives 27.6 million, because it ignores a −2.8n term. Merge sort needs about n log2 n = 19.9 million.
Chapter 6
Swap less with two pointers, and stop paying for duplicates with three regions
Lomuto has two weak spots. It swaps every low element, even one that is already on the left. And on an array of equal values, every element is "at or below" the pivot, so every split is n − 1 to 0.
Hoare partition is Hoare's original. It takes the first element as the pivot and uses two pointers:
It returns the crossing point j. Quicksort then recurses on (lo, j) and (j + 1, hi). The pivot is not always at j.
On 8, 1, 6, 4, 0, 3, 9, 5 with pivot 8, the pointers stop at 8 and 5 and swap them. Next they stop at 9 (index 6) and 3 (index 5). They have crossed, so Hoare returns j = 5 after one swap. The left part is 5, 1, 6, 4, 0, 3.
Three-way partition keeps three regions: below the pivot, equal to it, and above it. It uses three pointers: lt, i and gt. The equal region is final at once, so the recursion skips it.
Run it on 4, 2, 4, 1, 4, 3, 4, 2 with pivot 4. One pass ends with lt = 4 and gt = 7, and the array 2, 1, 3, 2, 4, 4, 4, 4. The four 4s need no more work. Only 2, 1, 3, 2 does.
Each scheme sorts the same 200 values with a random pivot. Pick the input and compare comparisons, swaps and stack depth.
This page measures the counts. A comparison is one test of an element against the pivot; three-way can make two tests per element, and the device counts both.
| Scheme | Swaps per partition, random data | All equal values | Pivot ends at |
|---|---|---|---|
| Lomuto | about n/2 | n − 1 to 0 split, n squared | its final index q |
| Hoare | about n/6 | near-even split | somewhere in A[lo..j] |
| Three-way | more than Hoare | one pass, done | the whole equal block |
The failure. Symptom: sorting 10 million ages (0 to 120) is far slower than sorting 10 million distinct IDs. Measure: count how many values are equal to each pivot. Fix: three-way partition.
Chapter 7
Run every pivot rule on every kind of input and read the cost in comparisons, swaps and depth
Each idea so far fixes one input. The lab puts them side by side. Pick a rule, pick an input, and sort. Depth here is the deepest chain of pending calls, the number Chapter 9 turns into stack memory.
Choose a rule and an input, then press Sort. Blue is the active range, warm the pivot, green a placed element.
Rule
Input
The introsort here is the textbook recipe: median of 3, insertion sort below 16 elements, heapsort when depth passes 2 log2 n. Library versions tune each part.
| Try | What to see |
|---|---|
| Last element, Sorted | n(n − 1)/2 comparisons and depth n − 1, in red. |
| Random, Sorted | The same input at near 2n ln n. |
| Median of 3, Sorted | Perfect middles: the best case. |
| Last element, 4 values | Equal runs give long chains. |
| Three-way, 4 values | Depth stays tiny; each value finishes in one pass. |
| Introsort, 4 values, size 120 | The depth limit trips and heapsort finishes the range. |
The worked number, at size 64. Last element on sorted input costs 64 × 63 / 2 = 2,016 comparisons. Chapter 5's formula predicts about 361 for a random pivot. Median of 3 on sorted input picks the true middle each time, so it lands near the best case.
The failure. Symptom: median of 3 is fine on sorted input but slow on some crafted inputs. Measure: watch the depth counter climb past 2 log2 n. Fix: a depth limit with a heapsort fallback, which is introsort (Chapter 9).
Chapter 8
Find the k-th smallest value without sorting, by throwing away the side that cannot hold it
You want the median response time of a server, not the whole sorted list. Sorting costs n log n. Partition already tells you more than you need: after it, the pivot sits at its sorted index q.
Call the index you want k, counting from 0. Compare k with q. If they are equal, the pivot is the answer. If k is smaller, the answer is on the left; if larger, on the right. Throw the other side away. This is quickselect, also by Hoare.
Set k, then press Step. Grey bars are out of the search. Blue is the range still searched; warm is the pivot.
Twenty made-up values from 1 to 20, random pivots. The device shows k from 1; the code uses k from 0.
How much work is it? Suppose each pivot cut the range in half. Call the array size n, and call the total comparisons W.
W equals n, plus n over 2, plus n over 4, and so on, which is less than 2 n.
Scan n, then half of n, then a quarter. Each scan is half the one before. The scans never add up to more than 2 times n.
n = 1,000: 1,000 + 500 + 250 + 125 + … stays under 2,000. A full sort costs about 1,000 × 10 = 10,000.
Random pivots do not halve exactly. In our simulation at n = 2,000, the median cost about 3.3n comparisons and the minimum about 2.1n. Both are linear in n. The worst case is still n squared. CLRS Chapter 9 builds a better pivot rule, the median of medians, that is linear even in the worst case.
The failure. Symptom: a "top 10" query sorts all 10 million rows. Measure: the cost grows like n log n as data grows. Fix: quickselect for index n − 10. Everything right of it is the top 10, in no particular order.
Chapter 9
Cap the stack, hand tiny ranges to insertion sort, and add a fallback that guarantees n log n
Python's default recursion limit is 1,000. Sort 50,000 sorted numbers with a last-element pivot, and the call chain is 49,999 deep. The program crashes before it is slow. The fix changes how you make the two calls.
Make one real call, on the smaller side. Then handle the larger side with a loop instead of a second call. CLRS calls this tail-recursion elimination. Call the size of a range m and the deepest chain of pending calls D.
D is at most log base 2 of n.
Each new frame works on the smaller side, so its m is at most half of its parent's m. After D frames, m has halved D times. m cannot go below 1, so D is at most log2 n.
n = 1,000,000: log2 n is about 19.9, so at most 19 frames are alive, whatever the pivots do.
The line is the number of pending calls during one sort of 256 values. The dashed line is log2 n = 8. Turn on smaller side first.
Measured on this page. Smaller side first caps the stack; it does not change the comparison count.
| Trick | What it does | Why |
|---|---|---|
| Insertion sort cutoff | Ranges under about 16 elements go to insertion sort. | Calls cost more than the sorting at that size. |
| Median of 3 | Pivot is the median of the first, middle and last values. | Sorted and reversed input split evenly, with no random numbers. |
| Introsort | Switch to heapsort when depth passes 2 log2 n. | Guarantees n log n in the worst case (Musser, 1997). |
Quicksort is also not stable: equal keys can change order. Sort (5, a), (3, b), (2, c), (5, d), (4, e) by number with Lomuto. The result is (3, b), (2, c), (4, e), (5, d), (5, a). The two 5s swapped places. When order among equal keys matters, use a stable sort such as merge sort.
The failure. Symptom: RecursionError on large sorted input. Measure: track the deepest call; it is near n. Fix: smaller side first, or an explicit stack, plus a random pivot.
Chapter 10
Keep the terms, the numbers, the code and the checks in one place
Quicksort partitions around a pivot, then sorts both sides. Its cost is set by the splits: even splits give n log n, one-sided splits give n squared. A random pivot makes n log n the expected cost on any input.
| Term | Meaning | Number to remember |
|---|---|---|
| Partition (Lomuto) | One pass that puts the pivot in its sorted place. | m − 1 comparisons on m elements |
| Worst case | Every split is m − 1 to 0. | n(n − 1)/2; 10 for n = 5 |
| Best case | Every pivot is the median. | about n log2 n; 7,987 for n = 1,000 |
| Pair chance | Ranks i and j are compared. | 2/(j − i + 1) |
| Expected comparisons | Average over random pivots, any input. | about 2n ln n = 1.39 n log2 n; 16.92 for n = 8 |
| Hoare partition | Two pointers that meet in the middle. | about n/6 swaps per partition |
| Three-way partition | Below, equal, above. | all equal values: one pass |
| Quickselect | Recurse on the side that holds index k. | linear expected; under 2n if every pivot halved |
| Stack depth | Pending calls, smaller side first. | at most log2 n |
| Introsort | Quicksort with a heapsort fallback. | depth limit 2 log2 n |
pythonimport random def partition(A, lo, hi): # Lomuto, random pivot r = random.randint(lo, hi); A[r], A[hi] = A[hi], A[r] pivot, i = A[hi], lo - 1 for j in range(lo, hi): if A[j] <= pivot: i += 1; A[i], A[j] = A[j], A[i] A[i + 1], A[hi] = A[hi], A[i + 1] return i + 1 def quicksort(A, lo=0, hi=None): # smaller side first: stack <= log2 n hi = len(A) - 1 if hi is None else hi while lo < hi: q = partition(A, lo, hi) if q - lo < hi - q: quicksort(A, lo, q - 1); lo = q + 1 else: quicksort(A, q + 1, hi); hi = q - 1 def quickselect(A, k): # k-th smallest, k from 0 lo, hi = 0, len(A) - 1 while True: q = partition(A, lo, hi) if lo < hi else lo if k == q: return A[q] lo, hi = (lo, q - 1) if k < q else (q + 1, hi)
Common C++ std::sort implementations use introsort. Java sorts primitive arrays with Yaroslavskiy's dual-pivot quicksort, which splits into three parts with two pivots. Python and Java's object sort use Timsort, a stable merge sort that is fast on input that is already partly in order.
Now press Present or Teach and explain from memory. Say the partition invariant. Say why a sorted array costs n(n − 1)/2. Say why two ranks meet with chance 2/(j − i + 1). Then go back to the hero and sort the 48 numbers again. This time say which chapter explains each count.
This lesson re-teaches Chapter 7, Quicksort, of Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). Quicksort is due to C. A. R. Hoare (1961). The text, toys and devices here are our own.