Quick Sort, step by step.

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

What is quick sort?

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.

How quick sort works: pivot, partition, recursion

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.

The array 5, 2, 1, 4, 0, 6, 3 with the pivot tag under its 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.

Arrows from 5, 2, 1, 4, 0, 6, 3 to its partition: 2, 1, 0 under a bracket for values smaller than the pivot, 3 in green, and 5, 6, 4 under a bracket for the rest.

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.

Arrows from each side to the side sorted: 2, 1, 0 becomes 0, 1, 2 and 5, 6, 4 becomes 4, 5, 6, all green, with 3 between them.

Lomuto partition scheme

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 marker at work

All steps as text
  1. Midway through the first partition: 2 and 1 are smaller than the pivot, the marker is on 5, and 4, 0 and 6 are not examined yet.
  2. Consider the element at index 3. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  3. Consider the element at index 4.
  4. Since this element is less than the pivot and a marked element exists, swap them.
  5. Increment the marker by one position after the swap.
  6. Consider the element at index 5. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  7. After comparing all elements with the pivot, swap the pivot with the marked element.
  8. Mark the pivot green, as it is now in its final position.
  9. The pivot swap put 3 between the regions: the smaller values 2, 1, 0 on its left and the rest, 5, 6, 4, on its right.
Quick Sort — The marker at work. Last step: The pivot swap put 3 between the regions: the smaller values 2, 1, 0 on its left and the rest, 5, 6, 4, on its right.

Quick sort example: 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.

The first partition

All steps as text
  1. Sort the array using the Quick Sort algorithm.
  2. Select the last element as the pivot.
  3. Consider the element at index 0.
  4. Mark this as the leftmost element not less than the pivot. Prepare to swap it with any subsequent element smaller than the pivot, and finally with the pivot itself to complete the partition.
  5. Consider the element at index 1.
  6. Since this element is less than the pivot and a marked element exists, swap them.
  7. Increment the marker by one position after the swap.
  8. Consider the element at index 2.
  9. Since this element is less than the pivot and a marked element exists, swap them.
  10. Increment the marker by one position after the swap.
  11. Consider the element at index 3. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  12. Consider the element at index 4.
  13. Since this element is less than the pivot and a marked element exists, swap them.
  14. Increment the marker by one position after the swap.
  15. Consider the element at index 5. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  16. After comparing all elements with the pivot, swap the pivot with the marked element.
  17. Mark the pivot green, as it is now in its final position.
  18. Six comparisons with the pivot, three swaps and one pivot swap: 3 is in its final place, with 2, 1, 0 to its left and 5, 6, 4 to its right.
Quick Sort — The first partition. Last step: Six comparisons with the pivot, three swaps and one pivot swap: 3 is in its final place, with 2, 1, 0 to its left and 5, 6, 4 to its right.

Quick sort example: sorting both parts

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.

Sorting both parts

All steps as text
  1. 3 is in its final place. The left part, 2, 1, 0, is sorted next in the same way, then the right part, 5, 6, 4.
  2. Focus on sorting the subarray obtained from the previous partitioning.
  3. Select the last element as the pivot.
  4. Consider the element at index 0.
  5. Mark this as the leftmost element not less than the pivot. Prepare to swap it with any subsequent element smaller than the pivot, and finally with the pivot itself to complete the partition.
  6. Consider the element at index 1. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  7. After comparing all elements with the pivot, swap the pivot with the marked element.
  8. Mark the pivot green, as it is now in its final position.
  9. Focus on sorting the subarray obtained from the previous partitioning.
  10. Select the last element as the pivot.
  11. Consider the element at index 1.
  12. Since the element is less than the pivot and no element is marked yet, leave it in place.
  13. Mark the pivot green, as it is now in its final position.
  14. Focus on sorting the subarray obtained from the previous partitioning.
  15. When a segment has only one element, treat it as sorted.
  16. Focus on sorting the subarray obtained from the previous partitioning.
  17. Select the last element as the pivot.
  18. Consider the element at index 4.
  19. Mark this as the leftmost element not less than the pivot. Prepare to swap it with any subsequent element smaller than the pivot, and finally with the pivot itself to complete the partition.
  20. Consider the element at index 5. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  21. After comparing all elements with the pivot, swap the pivot with the marked element.
  22. Mark the pivot green, as it is now in its final position.
  23. Focus on sorting the subarray obtained from the previous partitioning.
  24. Select the last element as the pivot.
  25. Consider the element at index 5.
  26. Mark this as the leftmost element not less than the pivot. Prepare to swap it with any subsequent element smaller than the pivot, and finally with the pivot itself to complete the partition.
  27. After comparing all elements with the pivot, swap the pivot with the marked element.
  28. Mark the pivot green, as it is now in its final position.
  29. Focus on sorting the subarray obtained from the previous partitioning.
  30. When a segment has only one element, treat it as sorted.
  31. The array is fully sorted.
  32. Six comparisons with the pivot and three pivot swaps sort both parts. The whole sort took five partitions: 12 comparisons with the pivot, three swaps and four pivot swaps.
Quick Sort — Sorting both parts. Last step: The array is sorted: 0, 1, 2, 3, 4, 5, 6.

Quick sort worst case: an example

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.

A worst-case array

All steps as text
  1. In 6, 2, 5, 3, 4, 1, 0 every pivot will be the smallest or the largest value of its segment.
  2. Select the last element as the pivot.
  3. Consider the element at index 0.
  4. Mark this as the leftmost element not less than the pivot. Prepare to swap it with any subsequent element smaller than the pivot, and finally with the pivot itself to complete the partition.
  5. Consider the element at index 1. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  6. Consider the element at index 2. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  7. Consider the element at index 3. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  8. Consider the element at index 4. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  9. Consider the element at index 5. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  10. After comparing all elements with the pivot, swap the pivot with the marked element.
  11. Mark the pivot green, as it is now in its final position.
  12. Focus on sorting the subarray obtained from the previous partitioning.
  13. Select the last element as the pivot.
  14. Consider the element at index 1.
  15. Since the element is less than the pivot and no element is marked yet, leave it in place.
  16. Consider the element at index 2.
  17. Since the element is less than the pivot and no element is marked yet, leave it in place.
  18. Consider the element at index 3.
  19. Since the element is less than the pivot and no element is marked yet, leave it in place.
  20. Consider the element at index 4.
  21. Since the element is less than the pivot and no element is marked yet, leave it in place.
  22. Consider the element at index 5.
  23. Since the element is less than the pivot and no element is marked yet, leave it in place.
  24. Mark the pivot green, as it is now in its final position.
  25. Focus on sorting the subarray obtained from the previous partitioning.
  26. Select the last element as the pivot.
  27. Consider the element at index 1.
  28. Mark this as the leftmost element not less than the pivot. Prepare to swap it with any subsequent element smaller than the pivot, and finally with the pivot itself to complete the partition.
  29. Consider the element at index 2. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  30. Consider the element at index 3. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  31. Consider the element at index 4. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  32. After comparing all elements with the pivot, swap the pivot with the marked element.
  33. Mark the pivot green, as it is now in its final position.
  34. Focus on sorting the subarray obtained from the previous partitioning.
  35. Select the last element as the pivot.
  36. Consider the element at index 2.
  37. Mark this as the leftmost element not less than the pivot. Prepare to swap it with any subsequent element smaller than the pivot, and finally with the pivot itself to complete the partition.
  38. Consider the element at index 3. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  39. Consider the element at index 4. Since it is not less than the pivot and the leftmost such element is already marked, take no action.
  40. After comparing all elements with the pivot, swap the pivot with the marked element.
  41. Mark the pivot green, as it is now in its final position.
  42. Focus on sorting the subarray obtained from the previous partitioning.
  43. Select the last element as the pivot.
  44. Consider the element at index 3.
  45. Since the element is less than the pivot and no element is marked yet, leave it in place.
  46. Consider the element at index 4.
  47. Since the element is less than the pivot and no element is marked yet, leave it in place.
  48. Mark the pivot green, as it is now in its final position.
  49. Focus on sorting the subarray obtained from the previous partitioning.
  50. Select the last element as the pivot.
  51. Consider the element at index 3.
  52. Since the element is less than the pivot and no element is marked yet, leave it in place.
  53. Mark the pivot green, as it is now in its final position.
  54. Focus on sorting the subarray obtained from the previous partitioning.
  55. When a segment has only one element, treat it as sorted.
  56. The array is fully sorted.
  57. Every partition left one side empty: 6, 5, 4, 3, 2 and 1 comparisons with the pivot, 21 in all, the most for seven values. Apart from three pivot swaps, nothing swapped.
Quick Sort — A worst-case array. Last step: The array is sorted: 0, 1, 2, 3, 4, 5, 6.

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.

Is quick sort stable?

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 is quick sort O(n²)?

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 partition scheme vs Lomuto

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 first partition of 5, 2, 1, 4, 0, 6, 3 in three rows. Scan: marker i, a red flag, stops on 5, the pivot, and marker j, a blue flag, on 3. Swap, scan: after the swap the array is 3, 2, 1, 4, 0, 6, 5, the pivot tag has moved under 5, and the markers stop again, j on 0 and i on 6, crossed. Split: 3, 2, 1, 4, 0 under a bracket for values not larger than the pivot and 6, 5 under one for values not smaller.

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.

Quick sort time complexity: best, average and worst case

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.

CaseComparisons (7 values)TimeStack space
Best: even splits10O(n log n)O(log n)
Average: random order13.5O(n log n)O(log n)
Worst: every pivot at an end21O(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 space complexity: is it in-place?

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.

Choosing the pivot in quick sort: random and median-of-three

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.

Why quick sort is not stable

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.

Two rows of three cells, labeled Before and After. Before holds 1, a 2 marked a and a 2 marked b, with the pivot tag under the 2 marked b and the marker flag over the 2 marked a. After holds 1, the 2 marked b in green, and the 2 marked a: the two equal 2s have changed order.
The pivot, the second 2, swaps with the marked first 2 and jumps over it. The input was already in order, yet the equal values end reversed, so quick sort is not stable.

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.

Quick sort vs merge sort vs heap sort: when to use it

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 →

Quick sort in Python, Java and C++

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

Three animations here.
The whole topic 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.

Hoare's partition

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.

Your own 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.

Theory and pivot choice

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.

Python, Java and C++

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.

Quiz

Eight questions with an explanation for every answer, from what partitioning does to which scheme always leaves the pivot in its final place.

Five more sorts

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.

Sort an array
one pivot at a time.

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