Quicksort

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.

Sort 48 numbers three ways

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

Sort in Place by Splitting Around a Pivot

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.

Pick a pivot and split

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.

12th

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).

The road

  1. Partition: the one pass, its invariant, and the codelab.
  2. The recursion: partition, then sort both sides.
  3. Worst and best case: why the split decides the cost.
  4. Random pivots: the hero's Random button.
  5. Expected comparisons: the 2n ln n proof.
  6. Hoare and three-way partition: fewer swaps, free duplicates.
  7. The sorting laboratory: every variant on every input.
  8. Quickselect: one side only, for the k-th smallest.
  9. In practice: stack depth, cutoffs, introsort, stability.
  10. Field guide: the numbers, the code, the credit.
After one partition of 12 distinct values, how many values are certain to be in their final sorted position?

Chapter 1

Partition: One Pass, One Pivot Placed

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.

  1. Set the pivot to A[hi]. Set i to lo − 1, so the low side is empty.
  2. For each j from lo to hi − 1, compare A[j] with the pivot.
  3. If A[j] is at or below the pivot, add 1 to i and swap A[i] with A[j].
  4. After the scan, swap A[i + 1] with the pivot. Return i + 1.

Step the partition

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.

The invariant

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.

Lomuto partition runs on a subarray of 8 elements. How many comparisons does it make?

Chapter 2

Quicksort: Partition, Then Recurse on Both Sides

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.

Grow the call tree

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.

Why it is correct

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.

Why must the recursive calls be on (lo, q − 1) and (q + 1, hi), and not on (lo, q)?

Chapter 3

Worst Case and Best Case: The Split Decides

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).

Say it aloud

C-worst of n equals n minus 1, plus n minus 2, down to 1. That is n times n minus 1, over 2.

Cworst(n)
C-worst of n the total comparisons when every split is as bad as it can be.
n
n the number of elements in the array.
n(n − 1)/2
n times n minus 1, over 2 the sum of 1 to n − 1. Pair the first and last terms: each pair adds to n.
In plain words

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.

With numbers

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).

Say it aloud

T of n equals two times T of n over 2, plus n.

T(n)
T of n the comparisons to sort n elements.
2 T(n/2)
two T of n over 2 two calls, each on half the elements.
n
n the partition scan at this level, about n comparisons.
In plain words

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.

With numbers

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.

Turn the split ratio

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.

50%

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.

Every partition splits 9 to 1. What is the running time?

Chapter 4

Randomized Quicksort: Beat the Bad Input

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.

Run the sorted input 40 times

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.

1,024

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.

What does randomized quicksort promise?

Chapter 5

Expected Comparisons: Count Pairs, Not Steps

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.

Say it aloud

The probability that z-i meets z-j equals 2 over j minus i plus 1.

Pr[zi meets zj]
the probability that z-i meets z-j the chance that the values of rank i and rank j are ever compared.
2
two the two winning first picks: zi itself or zj itself.
j − i + 1
j minus i plus 1 how many values lie from rank i to rank j, both ends included. Each has the same chance to be the first pivot.
In plain words

Count the values from z-i to z-j. Two of them make the pair meet. Divide 2 by that count.

With numbers

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.

Say it aloud

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.

E[X]
the expected value of X the average number of comparisons over the random pivot choices, for any fixed input.
Σi<j
the sum over i less than j one term for every pair of ranks, n(n − 1)/2 terms in all.
2n ln n
2 n ln n, said two n natural log of n the size of the sum for large n. It equals about 1.39 n log2 n.
In plain words

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.

With numbers

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.

Read the pair matrix

Cell (i, j) is the chance that ranks i and j meet. Tap a cell to read it. Change n and watch the sum.

8

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.

With n = 10, what is the chance that the smallest and the largest value are ever compared?

Chapter 6

Hoare and Three-Way Partition

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:

  1. The left pointer moves right until it finds a value at or above the pivot.
  2. The right pointer moves left until it finds a value at or below the pivot.
  3. If the pointers have not crossed, swap the two values and repeat.

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.

Race the three partitions

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.

SchemeSwaps per partition, random dataAll equal valuesPivot ends at
Lomutoabout n/2n − 1 to 0 split, n squaredits final index q
Hoareabout n/6near-even splitsomewhere in A[lo..j]
Three-waymore than Hoareone pass, donethe 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.

You sort 10 million records by age, an integer from 0 to 120. Which partition fits best?

Chapter 7

The Sorting Laboratory

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.

Sort it yourself

Choose a rule and an input, then press Sort. Blue is the active range, warm the pivot, green a placed element.

Rule

Input

64

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.

TryWhat to see
Last element, Sortedn(n − 1)/2 comparisons and depth n − 1, in red.
Random, SortedThe same input at near 2n ln n.
Median of 3, SortedPerfect middles: the best case.
Last element, 4 valuesEqual runs give long chains.
Three-way, 4 valuesDepth stays tiny; each value finishes in one pass.
Introsort, 4 values, size 120The 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).

Which input makes the last-element rule hit its worst case?

Chapter 8

Quickselect: Recurse on One Side Only

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.

Hunt the k-th smallest

Set k, then press Step. Grey bars are out of the search. Blue is the range still searched; warm is the pivot.

10th

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.

Say it aloud

W equals n, plus n over 2, plus n over 4, and so on, which is less than 2 n.

W
W the total comparisons quickselect makes.
n
n the first partition scans all n elements.
n/2 + n/4 + …
n over 2 plus n over 4, and so on each later scan covers half the range before it.
2n
two n the limit of the halving sum. Each term fills half the gap that is left to 2n.
In plain words

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.

With numbers

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.

After partition, the pivot is at q = 6 and you want k = 3. What does quickselect do?

Chapter 9

Quicksort in Practice: Stack, Cutoffs and Introsort

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.

Say it aloud

D is at most log base 2 of n.

D
D the most stack frames alive at once, with smaller side first.
log2 n
log base 2 of n how many times you can halve n before you reach 1.
In plain words

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.

With numbers

n = 1,000,000: log2 n is about 19.9, so at most 19 frames are alive, whatever the pivots do.

Watch the stack

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.

Three more tricks

TrickWhat it doesWhy
Insertion sort cutoffRanges under about 16 elements go to insertion sort.Calls cost more than the sorting at that size.
Median of 3Pivot is the median of the first, middle and last values.Sorted and reversed input split evenly, with no random numbers.
IntrosortSwitch 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.

Why does recursing on the smaller side first cap the stack at log2 n?

Chapter 10

Field Guide

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.

TermMeaningNumber to remember
Partition (Lomuto)One pass that puts the pivot in its sorted place.m − 1 comparisons on m elements
Worst caseEvery split is m − 1 to 0.n(n − 1)/2; 10 for n = 5
Best caseEvery pivot is the median.about n log2 n; 7,987 for n = 1,000
Pair chanceRanks i and j are compared.2/(j − i + 1)
Expected comparisonsAverage over random pivots, any input.about 2n ln n = 1.39 n log2 n; 16.92 for n = 8
Hoare partitionTwo pointers that meet in the middle.about n/6 swaps per partition
Three-way partitionBelow, equal, above.all equal values: one pass
QuickselectRecurse on the side that holds index k.linear expected; under 2n if every pivot halved
Stack depthPending calls, smaller side first.at most log2 n
IntrosortQuicksort with a heapsort fallback.depth limit 2 log2 n

Check before you trust a quicksort

  1. Empty array and one element: return at once.
  2. Two elements, [2, 1]: comes out [1, 2].
  3. Sorted and reversed input of 10,000: finishes fast with no RecursionError.
  4. All equal values: finishes, and fast if you use three-way partition.
  5. Lomuto returns i + 1; recursion uses q − 1 and q + 1. Hoare recursion uses j and j + 1.

The core, in code

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)

Where it sits in the field

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.

Keep going

The takeaway. Quicksort is one partition repeated. Pick the pivot at random, and the input can no longer choose your splits; the expected cost is then about 2n ln n on any input.
Which change turns quicksort's n squared worst case into a guaranteed n log n?

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.

Credit and source

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.

CLRS Chapter 7: Quicksort
Introduction to Algorithms (MIT Press) · Back to Gleams