Quick sort is a divide-and-conquer sorting algorithm that picks a pivot, moves the smaller values before it and the others after it, and sorts both sides the same way. It takes O(n log n) time on average and O(n²) in the worst case, sorts in place with an O(log n) recursion stack on average and is not stable. This page explains how it works, with step-by-step animations of the first partition, the sorting of both parts and a worst-case array from the VisiGrab app.
// how quick sort works
Quick sort, also called partition-exchange sort, is a divide-and-conquer sorting algorithm. It picks a value, the pivot, moves the smaller values before it and the rest after it, and sorts both sides the same way. It takes O(n log n) time on average and O(n2) in the worst case. It sorts in place, with an O(log n) recursion stack on average, and is not stable. Tony Hoare devised it in 1959.
Each call sorts one segment, the cells from index low to high, in three steps. The diagrams show them on the app's default array, 5, 2, 1, 4, 0, 6, 3.
1. Pick a pivot, here the segment's last value, 3.
2. Partition: move the values smaller than the pivot before it and the rest after it. Every value before the pivot is smaller and none after it is, so the pivot is in its final place.
3. Recurse: the function calls itself on both sides, and each comes back sorted. A segment of one value or none is sorted, so the recursion stops there.
The Lomuto scheme, the app's default, takes the segment's last value as the pivot. An index j examines the other values from left to right, and an index i marks the leftmost value not smaller than the pivot. Each smaller value that j finds swaps with the value at i, and i moves one place right. A final pivot swap puts the pivot at i. In pseudocode:
quickSort(a, low, high)
if low < high
p = partition(a, low, high)
quickSort(a, low, p - 1)
quickSort(a, p + 1, high)
partition(a, low, high)
pivot = a[high]
i = low
for j from low to high - 1
if a[j] < pivot
swap a[i] and a[j]
i = i + 1
swap a[i] and a[high]
return i
quickSort partitions only while low < high. Swapping a[i] and a[high] places the pivot, and partition returns its index, i. quickSort keeps it in p, shortened here from pivotIndex in the app's pseudocode. A segment of k values makes k − 1 comparisons. The first call is quickSort(a, 0, n - 1).
In the app the examined value, at j, turns yellow, and a "pivot" tag sits under the pivot. A flag, the marker, shows i, but only from the first value not smaller than the pivot. The values before the marker are smaller than the pivot, the ones from the marker up to j are not, and the rest are not examined yet. A < pivot bracket grows under the smaller values gathered on the left. The pivot swap adds a ≥ pivot bracket under the values after it, and the pivot, now final, turns green. Over the array below, labels follow these regions through the end of the first partition.
The player runs the first partition of the app's default array, 5, 2, 1, 4, 0, 6, 3, with the pivot 3. 2, 1 and 0 are smaller and swap to the front, and the pivot swap puts 3 between them and the rest: 2, 1, 0, 3, 5, 6, 4.
3 is in its final place. The player sorts the left part, 2, 1, 0, and the right part, 5, 6, 4, the same way while the rest is dimmed: two partitions each, and a part of one value is already sorted.
The worst case comes when every pivot is the smallest or the largest value of its segment. Each partition then leaves one side empty, and the next segment is only one value shorter. In 6, 2, 5, 3, 4, 1, 0 the pivots are 0, 6, 1, 2, 5 and 4 in turn, each the smallest or the largest of its segment, and 3 is left alone.
Six partitions make 6, 5, 4, 3, 2 and 1 comparisons: n(n − 1)/2 = 21, the most for seven values. Of the 5,040 orders of seven distinct values, 64 are this slow. The common ones are input already in order: sorted, where every pivot is the largest, and reversed. Seven equal values make 21 too: none is smaller than the pivot. Three-way partitioning, Dijkstra's Dutch national flag, gathers values equal to the pivot in the middle and sorts all-equal input in one pass.
No. A swap can carry a value past an equal one, so equal values can end up in reversed order; the example below shows how.
When every pivot is the smallest or the largest value of its segment: each partition then leaves one side empty, and n − 1 partitions make n(n − 1)/2 comparisons. With a fixed end pivot, sorted and reversed input do this; a random pivot makes it unlikely, but in the Lomuto scheme all-equal input does it whatever the pivot. The fourth player sorts a worst-case array.
Hoare's scheme, as in the app, takes the segment's first value as the pivot. Index i moves right to a value not smaller than the pivot, and j moves left to a value not larger. While i is still left of j, the two values swap and both scans go on; once they meet or cross, the partition ends. In pseudocode:
quickSort(a, low, high)
if low < high
p = partition(a, low, high)
quickSort(a, low, p)
quickSort(a, p + 1, high)
partition(a, low, high)
pivot = a[low]
i = low - 1
j = high + 1
while true
repeat
i = i + 1
until a[i] >= pivot
repeat
j = j - 1
until a[j] <= pivot
if i >= j
return j
swap a[i] and a[j]
As i starts at low - 1 and j at high + 1, each repeat moves its index at least once. When i >= j, partition returns j: nothing in a[low..j] is larger than the pivot, and nothing after it is smaller. The pivot may sit on either side, so the recursion covers a[low..p] and a[p + 1..high]; the app's pseudocode calls p partitionIndex.
On the default array, i stops at once on the pivot, 5, and j on 3. They swap: 3, 2, 1, 4, 0, 6, 5. Then i stops on 6 and j on 0: they have crossed, so the segment splits after j, at index 4, into 3, 2, 1, 4, 0 and 6, 5. The pivot sits at index 6, not at its final index 5.
Hoare's scheme makes about three times fewer swaps on average, though not fewer comparisons, and splits equal values evenly. It must not take the last value as its pivot: if that value is the largest, both scans stop on it, partition returns high, and the same segment recurses forever.
Hoare's scheme is in the app too. In VisiGrab, switch the partition scheme from Lomuto to Hoare and step through it like the players on this page: the two markers scanning from both ends, every swap, the crossing and the split, in 59 steps on the default array, or on a random array or one of your own.
Each level of the recursion partitions at most n values: O(n). Even splits give about log2 n levels, so T(n) = 2T(n/2) + O(n) is O(n log n). A smallest or largest pivot every time gives n levels, so T(n) = T(n − 1) + O(n) is O(n2). Random order averages about 1.39 n log2 n comparisons for large n.
| Case | Comparisons (7 values) | Time | Stack space |
|---|---|---|---|
| Best: even splits | 10 | O(n log n) | O(log n) |
| Average: random order | 13.5 | O(n log n) | O(log n) |
| Worst: every pivot at an end | 21 | O(n2) | O(n) |
The counts cover all 5,040 orders of seven distinct values in the app's Lomuto scheme; the default array takes 12.
Quick sort is in-place: it only swaps values inside the array. Its extra memory is the recursion stack, as deep as the calls nest: the recursion depth. Even splits keep it near log2 n, O(log n). On sorted input the app's code nests seven calls for seven values: O(n). Recursing into the smaller side and looping on the larger, in place of the last call, the tail call, keeps it O(log n) in every case: each nested call gets at most half the values.
A fixed end pivot makes sorted and reversed input, both common, the worst case. The middle value fixes sorted input, but other orders can still defeat it. A random pivot gives O(n log n) expected time on any input, without a guarantee. Median-of-three takes the middle one of the first, middle and last values and cuts the average to about 1.188 n log2 n comparisons. The app's info dialog shows both in pseudocode.
A stable sort keeps equal values in their original order. In 1, 2a, 2b the pivot is 2b. 1 is smaller; 2a is not, so the marker goes on it. The pivot swap carries 2b over 2a: 1, 2b, 2a. Both sides hold one value, so the sort ends there.
Hoare's scheme is unstable too. Neither scheme is adaptive: input already in order is sorted no faster, and with an end pivot it is the worst case.
On 5, 2, 1, 4, 0, 6, 3 quick sort makes 12 comparisons, merge sort and insertion sort 14 each, and heap sort 20. The merge sort page compares them in a table. Quick sort suits large arrays in memory, where it is usually the fastest: it reads the array in order, swaps in place and has a short inner loop. It is avoided when equal values must keep their order, when O(n log n) must be guaranteed, on linked lists and for data too large for memory. Quick sort vs merge sort: full comparison →
The app shows both schemes in all three. Its Lomuto listings also swap a value with itself, twice on the default array, which the animation skips. On sorted input the recursion nests one call per value, and the languages fail differently when the stack runs out.
Note
The app's Python listing raises RecursionError on an already sorted list of 1,000 values, as Python's default recursion limit is 1,000 calls. Java throws StackOverflowError when the thread's stack runs out, and in C++ a stack overflow usually crashes the program.
Many library sorts build on quick sort. C++'s std::sort is an introsort in GCC and, since LLVM 14, in LLVM. Introsort is quick sort that switches to heap sort when the recursion gets too deep and to insertion sort for small parts. Java sorts int, long, float and double arrays with a dual-pivot quicksort, which splits around two pivots into three parts; since Java 14 it too falls back to heap sort. Objects get TimSort. Python's list.sort() and sorted() use Timsort, with Powersort's merge order since Python 3.11, and never quick sort. NumPy's default kind='quicksort' is in fact an introsort.
The full source code is on GitHub, in Python, Java and C++.
// in the app
In VisiGrab quick sort runs on the default, a random or your own array of seven values, and you can step forward and back through every pivot, comparison, marker move, swap and green mark: 46 steps on the default array.
A panel in the corner switches the partition scheme from Lomuto to Hoare and restarts the run on the same array, and the app remembers the choice. Two markers then scan from both ends, swap and cross, and brackets split each segment in two: 59 steps on the default array.
A random array holds seven distinct values from 0 to 19. A seven-cell dialog takes your own values from 0 to 99, equal ones included, and its ascending fill gives the Lomuto worst case: 62 steps and 21 comparisons.
Two tabs. Info covers divide and conquer, in-place sorting with O(log n) auxiliary space, instability, non-adaptivity and the three cases. Partition has four pages: partition schemes, Lomuto and Hoare with pseudocode, and pivot selection by a random pivot or median-of-three.
The quickSort and partition methods for both schemes in Java and quick_sort and partition for both in Python and C++, with notes on how the animation draws the markers and links to the full source on GitHub. After the last step, a hint points to the code.
Eight questions with an explanation for every answer, from what partitioning does to which scheme always leaves the pivot in its final place.
Bubble, selection, insertion, merge and heap sort each have a topic of their own. The seven-value ones share your last random or custom array with this one.
// build your own
Download VisiGrab and step through every partition, Lomuto's or Hoare's, on the default array, a random one or an array of your own.
Quick sort is one of 30+ topics. See them all