Skip to main content

Quicksort

Quicksort, invented by Tony Hoare around 1960, is one of the most important algorithms ever designed. It is the basis of the sorting routines of many programming languages and libraries, and it is usually the fastest general-purpose sorting algorithm in practice. It improves the idea of exchange: instead of exchanging adjacent elements, it exchanges elements that are far apart, removing many inversions at once.

Quicksort is also our first example of a recursive algorithm based on divide and conquer, a paradigm that you will study in depth later in the course.

What you will learn in this lesson
  • The idea of partitioning around a pivot, and why it leads to a recursive algorithm.
  • The criteria for choosing the pivot, and the median-of-three strategy.
  • How the partitioning strategy works, step by step, with a complete trace.
  • Why Quicksort is O(nlog⁡n)O(n \log n) in the best and average cases but O(n2)O(n^2) in the worst case.
  • Its practical weaknesses (recursion depth, repeated keys, small subarrays) and how professional implementations address them.

The Idea: Partitioning​

Quicksort is based on partitioning. Choose an element of the vector, called the pivot, and rearrange the vector so that:

  • all the elements smaller than the pivot are on its left;
  • all the elements greater than the pivot are on its right;
  • the pivot is between them.

After partitioning, the pivot is in its final position: it will not move again. And the two parts on each side can be sorted independently, because no element will ever need to cross from one side to the other. So we apply the same idea to each part, recursively, until the parts have one element (or none), which are trivially sorted.

The tree of partitions of Quicksort: each pivot ends in its final position231476partition around 412367partition each part137one element: sortedorange: pivot of each part, already in its final position
The tree of partitions. After each partition the pivot (orange) is in its final position, and the two parts on each side are sorted independently.

The sequence of partitions forms a tree. If each pivot divides its part into two halves of similar size, the tree is balanced and has about log⁡2n\log_2 n levels. If the pivot is always at one end of its part (the smallest or the largest element), one of the parts is empty and the "tree" degenerates into a list of nn levels. This is the key to the efficiency of Quicksort, as we will see in the analysis: the choice of the pivot is crucial.


Choosing the Pivot​

The ideal pivot is the median of the elements (the element that would be in the middle if they were sorted), because it divides the part into two halves of equal size. The options are:

CriterionAssessment
The medianThe ideal solution, but it is very expensive to compute exactly.
The first element"Cheap", but a bad choice: on data that is already sorted (very common in practice), it is always the smallest element, and every partition is completely unbalanced.
The last elementSame problem as the first one.
A random elementStatistically, it is not a bad choice: no particular input is consistently bad. It has the cost of generating random numbers.
The central elementStatistically not a bad choice, and it works very well on sorted or reverse-sorted data.
Median-of-threeA compromise: take three elements (the first, the last and the central one), and use their median as the pivot. It does not guarantee anything, but it is a good indicator of the real median at a very low cost.

The course implementation uses the median-of-three. It sorts the three elements among themselves (so the smallest ends up at the left end and the largest at the right end) and returns the position of the central one, which holds their median:

private int medianOfThree(int[] elements, int left, int right) {
int center = left + (right - left) / 2;
if (elements[left] > elements[center]) Util.swap(elements, left, center);
if (elements[left] > elements[right]) Util.swap(elements, left, right);
if (elements[center] > elements[right]) Util.swap(elements, center, right);
return center; // elements[left] <= elements[center] <= elements[right]
}

A useful side effect: if the part has three elements or fewer, the median-of-three has already sorted it completely, and the recursion can stop there.


The Partitioning Strategy​

Once the pivot is chosen, the partition is done in place with two indices that move towards each other:

  1. Hide the pivot: exchange it with the last element, so that it does not get in the way.
  2. Move i from the left until it finds an element greater than the pivot (an element that should be on the right).
  3. Move j from the right until it finds an element smaller than the pivot (an element that should be on the left).
  4. If i and j have not crossed, exchange those two elements: each one goes to its correct side.
  5. Repeat steps 2 to 4 until i and j cross. Then i marks the first position of the right part: place the pivot there by exchanging it with the last element.
private void quickSortRecursive(int[] elements, int left, int right) {
if (left >= right) return; // 0 or 1 elements: sorted
int center = medianOfThree(elements, left, right);
if ((right - left) >= 3) { // with 3 elements or fewer, already sorted
int pivot = elements[center];
Util.swap(elements, center, right); // hide the pivot at the end
int i = left;
int j = right - 1;
do {
while (elements[i] <= pivot && i < right) i++; // first element > pivot
while (elements[j] >= pivot && j > left) j--; // first element < pivot
if (i < j) Util.swap(elements, i, j);
} while (i < j);
Util.swap(elements, i, right); // place the pivot in its final position
quickSortRecursive(elements, left, i - 1); // sort the left part
quickSortRecursive(elements, i + 1, right); // sort the right part
}
}

public void sort(int[] elements) {
quickSortRecursive(elements, 0, elements.length - 1);
}

Complete trace​

Let us sort 4 5 6 1 3 2 7 8 (positions 0 to 7).

ActionVectorComment
Median-of-three of 4, 1, 8 (positions 0, 3, 7)1 5 6 4 3 2 7 8The three are sorted among themselves; the pivot is 4.
Hide the pivot at the end1 5 6 8 3 2 7 4The 8 goes to position 3.
i stops at 5 (greater than 4), j stops at 2 (smaller than 4): swap1 2 6 8 3 5 7 4
i stops at 6, j stops at 3: swap1 2 3 8 6 5 7 4
i stops at 8 (position 3), j stops at 3 (position 2): they cross1 2 3 8 6 5 7 4No swap.
Place the pivot at position i = 31 2 3 4 6 5 7 8The 4 is in its final position.
First partition of Quicksort on 4 5 6 1 3 2 7 8, with the indices i and j0123456715643278median of 4, 1, 8 is 4: pivot = 415683274hide the pivot at the end12683574iji stops at 5, j stops at 2: swap12386574iji stops at 6, j stops at 3: swap12386574iji and j cross: stop12346578place the pivot at position i = 3≤ 4≥ 4
The first partition step by step. The index i (blue) looks for elements greater than the pivot and j (purple) for smaller ones; each pair found is exchanged, and when they cross the pivot moves to position i.
ProofQuicksort's partition is correct

Analysis​

Partitioning a part of mm elements costs O(m)O(m): each element is compared with the pivot about once, as i and j sweep the part. The total cost therefore depends on how balanced the partitions are.

The pivot always divides the part into two halves. Read the cost directly from the code: sorting nn elements means partitioning them (about nn steps) and then sorting two halves of n/2n/2 elements. If T(n)T(n) is the time to sort nn elements, that sentence written as an equation is:

T(n)=2 T ⁣(n2)⏟sort the two halves+O(n)⏟partitionT(n) = \underbrace{2\,T\!\left(\frac{n}{2}\right)}_{\text{sort the two halves}} + \underbrace{O(n)}_{\text{partition}}

It is not magic: it is the code, described in one line. To see what it adds up to, follow it with n=16n = 16:

LevelPartsSize of each partPartition work at the level
011616
12816
24416
38216
Total64

At every level the parts together contain the nn elements, so every level costs about nn. The sizes halve until they reach 1, which takes log⁡2n\log_2 n levels (log⁡216=4\log_2 16 = 4). Total: nn per level times log⁡2n\log_2 n levels, 16⋅4=6416 \cdot 4 = 64:

T(n)∈O(nlog⁡n)T(n) \in O(n \log n)

The divide and conquer chapter turns this reasoning into a general formula for this kind of equation, called a recurrence.

Balanced partitions give log n levels; a pivot at one end every time gives n levelspivot in the middle: log₂ n levelsnn per leveln/2n/2n per leveln/4n/4n/4n/4n per leveln/8n/8n/8n/8n/8n/8n/8n/8n per leveltotal ≈ n log₂ npivot always at one end: n levelsnn − 1n − 2n − 3⋮total ≈ n + (n − 1) + … + 1 ≈ n²/2
The two extremes of the tree of partitions. With balanced pivots there are about log₂ n levels, each costing n; with a pivot at one end every time, there are n levels of decreasing size, and the cost is quadratic.

We checked the effect of the pivot by counting comparisons with n=1,000n = 1{,}000 (the theoretical value of nlog⁡2nn \log_2 n is about 9,966):

PivotSortedRandomReverse
Median-of-three9,541 comparisons, depth 915,370 comparisons, depth 1810,539 comparisons, depth 9
First element499,500 comparisons, depth 99912,563 comparisons, depth 25499,500 comparisons, depth 999

With the first element as pivot, sorted and reverse inputs trigger the worst case: exactly n(n−1)2\frac{n(n-1)}{2} comparisons and a recursion as deep as the array is long. With median-of-three, the same inputs are actually the easiest ones.

Properties​

PropertyQuicksort
Best caseO(nlog⁡n)O(n \log n)
Average caseO(nlog⁡n)O(n \log n)
Worst caseO(n2)O(n^2)
Extra memoryThe recursion stack: O(log⁡n)O(\log n) in the best and average cases, O(n)O(n) in the worst case
StableNo: partitioning exchanges distant elements
AdaptiveNot in general

In practice, Quicksort is very fast for n>20n \gt 20: its inner loops are very simple and it accesses memory sequentially, which modern processors handle very efficiently. For very small parts, simple algorithms are faster.

ProofThe average cost of Quicksort

Practical Weaknesses and Improvements​

Recursion depth​

In the worst case, the recursion reaches a depth of nn, which can exhaust the call stack. The standard fix is to recurse only on the smaller part and handle the larger part with a loop. Since the smaller part has at most half the elements, the depth is then at most log⁡2n\log_2 n, whatever the pivots.

Many repeated keys​

Look at the scanning loops: i advances while elements[i] <= pivot, and j retreats while elements[j] >= pivot. If all the elements are equal, i runs to the end of the part, the pivot is placed at the last position, and every partition is completely unbalanced: quadratic time. We measured it with the course implementation: sorting 20,000 equal elements took about 97 ms (and 25 ms for 10,000: the time quadruples when nn doubles), versus about 2 ms for 20,000 random elements. With 50,000 equal elements, the recursion is so deep that it ends with a StackOverflowError.

Arrays with many repeated keys are very common (sorting people by age, or orders by status). Two well-known solutions:

  • stop both scans at elements equal to the pivot (< and > instead of <= and >=) and exchange them; this splits runs of equal keys evenly between both sides;
  • use a three-way partition (the "Dutch national flag" problem, studied by Dijkstra), which divides the part into elements smaller than, equal to and greater than the pivot, and recurses only on the first and last groups. With many equal keys, it becomes much faster than standard Quicksort.

Small parts​

For parts of fewer than about 10 to 20 elements, the overhead of recursion outweighs its benefits. Many implementations stop the recursion at that size and finish with insertion sort, which is very fast on small and almost sorted arrays (the parts are already roughly in their final zones).

Guaranteeing O(nlog⁡n)O(n \log n)​

Even with a good pivot strategy, an adversary can construct inputs that make Quicksort quadratic. Introsort monitors the recursion depth and, if it exceeds a multiple of log⁡n\log n, switches to another algorithm that guarantees O(nlog⁡n)O(n \log n). It is used in several standard libraries. Java's Arrays.sort for primitive types uses a highly tuned dual-pivot Quicksort, which partitions into three parts using two pivots.

Parallelism​

After a partition, the two parts are completely independent, so they can be sorted in parallel by different threads. This makes Quicksort a natural candidate for the parallel algorithms chapter.

🧠 Checkpoint: Which pivot strategy?

Question: A program sorts, every night, a list of transactions that is usually already sorted except for a few hundred new transactions appended at the end. Which pivot strategy would you avoid? Is Quicksort even the best choice here?

Answer: Avoid the first or last element: on almost sorted data, they produce extremely unbalanced partitions, with quadratic time and a risk of stack overflow. Median-of-three or the central element work well. But for almost sorted data, an adaptive algorithm is better still: insertion sort (if there are very few misplaced elements) or an algorithm that detects sorted runs, such as Mergesort-based TimSort, which Java uses for objects.


Measurements​

Times in milliseconds, without optimization (-Xint), with the course implementation:

nnSortedRandomReverse
4,0000.71.90.9
8,0001.63.71.8

For n=8,000n = 8{,}000 random elements, Quicksort takes about 4 ms, while insertion sort takes 329 ms and bubble sort more than a second. And the gap grows with nn: doubling the size roughly doubles the time of Quicksort (a little more, because of the log⁡n\log n factor), while it quadruples the time of the simple algorithms.

Common mistakes
  • Taking the first element as pivot. Sorted or reverse-sorted inputs then give O(n2)O(n^2); use the median of three.
  • Including the pivot in a recursive call. A part may not shrink and the recursion never ends; exclude the pivot.
  • Reading the average case as a guarantee. The worst case is still O(n2)O(n^2).
  • Ignoring the recursion depth. In the worst case it reaches nn; recursing first on the smaller part keeps it in O(log⁡n)O(\log n).

Summary​

  • Quicksort partitions the vector around a pivot, which ends in its final position, and sorts both parts recursively.
  • The pivot choice is crucial: the first or last element is cheap but disastrous on sorted data; median-of-three is a good compromise; a random pivot makes the expected cost O(nlog⁡n)O(n \log n) for every input.
  • Best and average cases: O(nlog⁡n)O(n \log n). Worst case: O(n2)O(n^2). It is in place (apart from the recursion stack) but not stable.
  • Practical improvements: recurse on the smaller part (stack depth O(log⁡n)O(\log n)), handle repeated keys (three-way partition), switch to insertion sort for small parts, and fall back to another O(nlog⁡n)O(n \log n) algorithm when the recursion gets too deep (Introsort).

Practice​

  • ✍️ Trace it. Sort 5 6 1 3 9 8 7 4 2 by hand with the course version of Quicksort (median-of-three, hiding the pivot at the end). Draw the tree of recursive calls.
  • 🔴 Find the worst case. Using the first element as pivot, which inputs of size 8 make Quicksort perform the maximum number of comparisons? Implement this version and count the comparisons for sorted data with n=1,000,2,000,4,000n = 1{,}000, 2{,}000, 4{,}000.
  • 🟰 Repeated keys. Measure the course implementation on arrays of equal elements and on arrays with only 3 different values, for increasing sizes. Then implement a three-way partition and repeat the measurements.
  • 📏 Limit the stack. Modify the implementation so that it recurses only on the smaller part. Check, by counting the maximum depth, that it never exceeds log⁡2n\log_2 n.
  • 🧩 Hybrid. Add a threshold kk below which parts are sorted with insertion sort. Measure the total time for k=0,5,10,20,50k = 0, 5, 10, 20, 50. Which threshold works best on your machine?
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.