1. Home
  2. Design & Analysis of Algorithms
  3. Quick Sort

Quick Sort

Pick a pivot, split the array into "smaller" and "bigger", and the pivot lands in its final spot. See the partition happen in 3D.

Interactive 3DIntermediate13 min readDAAUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

Quick sort picks a pivot, then partitions the array: smaller values to its left, bigger values to its right. The pivot is then in its final place, and we repeat on each side.

Pseudocode

  1. procedure quickSort(a, lo, hi):
  2. if lo ≥ hi: return
  3. pivot ← a[hi]; i ← lo − 1
  4. for j ← lo to hi − 1:
  5. if a[j] ≤ pivot:
  6. i ← i + 1
  7. swap(a[i], a[j])
  8. swap(a[i + 1], a[hi]) // pivot lands in its final place
  9. quickSort(a, lo, i)
  10. quickSort(a, i + 2, hi)
Read this model as text · 48 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. Quick sort picks a pivot, then partitions the array: smaller values to its left, bigger values to its right. The pivot is then in its final place, and we repeat on each side.
  2. quickSort(0..9): choose the last element 8 as the pivot (it steps forward). i starts at -1, just before the range.
  3. a[0] = 12 > pivot 8 → leave it where it is; it belongs on the right.
  4. a[1] = 5 ≤ pivot 8 → it belongs on the left. Increase i to 0 and swap a[0] with a[1].
  5. Swapped 5 and 12. Everything up to i is ≤ pivot (cyan); between i and j is > pivot (purple).
  6. a[2] = 12 > pivot 8 → leave it where it is; it belongs on the right.
  7. a[3] = 8 ≤ pivot 8 → it belongs on the left. Increase i to 1 and swap a[1] with a[3].
  8. Swapped 8 and 12. Everything up to i is ≤ pivot (cyan); between i and j is > pivot (purple).
  9. a[4] = 3 ≤ pivot 8 → it belongs on the left. Increase i to 2 and swap a[2] with a[4].
  10. Swapped 3 and 12. Everything up to i is ≤ pivot (cyan); between i and j is > pivot (purple).
  11. a[5] = 8 ≤ pivot 8 → it belongs on the left. Increase i to 3 and swap a[3] with a[5].
  12. Swapped 8 and 12. Everything up to i is ≤ pivot (cyan); between i and j is > pivot (purple).
  13. a[6] = 5 ≤ pivot 8 → it belongs on the left. Increase i to 4 and swap a[4] with a[6].
  14. Swapped 5 and 12. Everything up to i is ≤ pivot (cyan); between i and j is > pivot (purple).
  15. a[7] = 15 > pivot 8 → leave it where it is; it belongs on the right.
  16. a[8] = 8 ≤ pivot 8 → it belongs on the left. Increase i to 5 and swap a[5] with a[8].
  17. Swapped 8 and 12. Everything up to i is ≤ pivot (cyan); between i and j is > pivot (purple).
  18. Put the pivot between the two parts: swap a[6] and a[9]. 8 is now in its final position (index 6) — it will never move again.
  19. quickSort(0..5): choose the last element 8 as the pivot (it steps forward). i starts at -1, just before the range.
  20. a[0] = 5 ≤ pivot 8 → it belongs on the left. Increase i to 0 (i == j, no swap needed).
  21. a[1] = 8 ≤ pivot 8 → it belongs on the left. Increase i to 1 (i == j, no swap needed).
  22. a[2] = 3 ≤ pivot 8 → it belongs on the left. Increase i to 2 (i == j, no swap needed).
  23. a[3] = 8 ≤ pivot 8 → it belongs on the left. Increase i to 3 (i == j, no swap needed).
  24. a[4] = 5 ≤ pivot 8 → it belongs on the left. Increase i to 4 (i == j, no swap needed).
  25. Put the pivot between the two parts: swap a[5] and a[5]. 8 is now in its final position (index 5) — it will never move again.
  26. quickSort(0..4): choose the last element 5 as the pivot (it steps forward). i starts at -1, just before the range.
  27. a[0] = 5 ≤ pivot 5 → it belongs on the left. Increase i to 0 (i == j, no swap needed).
  28. a[1] = 8 > pivot 5 → leave it where it is; it belongs on the right.
  29. a[2] = 3 ≤ pivot 5 → it belongs on the left. Increase i to 1 and swap a[1] with a[2].
  30. Swapped 3 and 8. Everything up to i is ≤ pivot (cyan); between i and j is > pivot (purple).
  31. a[3] = 8 > pivot 5 → leave it where it is; it belongs on the right.
  32. Put the pivot between the two parts: swap a[2] and a[4]. 5 is now in its final position (index 2) — it will never move again.
  33. quickSort(0..1): choose the last element 3 as the pivot (it steps forward). i starts at -1, just before the range.
  34. a[0] = 5 > pivot 3 → leave it where it is; it belongs on the right.
  35. Put the pivot between the two parts: swap a[0] and a[1]. 3 is now in its final position (index 0) — it will never move again.
  36. [5] is a single element, so it is already in its final place.
  37. quickSort(3..4): choose the last element 8 as the pivot (it steps forward). i starts at 2, just before the range.
  38. a[3] = 8 ≤ pivot 8 → it belongs on the left. Increase i to 3 (i == j, no swap needed).
  39. Put the pivot between the two parts: swap a[4] and a[4]. 8 is now in its final position (index 4) — it will never move again.
  40. [8] is a single element, so it is already in its final place.
  41. quickSort(7..9): choose the last element 12 as the pivot (it steps forward). i starts at 6, just before the range.
  42. a[7] = 15 > pivot 12 → leave it where it is; it belongs on the right.
  43. a[8] = 12 ≤ pivot 12 → it belongs on the left. Increase i to 7 and swap a[7] with a[8].
  44. Swapped 12 and 15. Everything up to i is ≤ pivot (cyan); between i and j is > pivot (purple).
  45. Put the pivot between the two parts: swap a[8] and a[9]. 12 is now in its final position (index 8) — it will never move again.
  46. [12] is a single element, so it is already in its final place.
  47. [15] is a single element, so it is already in its final place.
  48. Sorted with 22 comparisons and 12 swaps. Average case O(n log n); worst case O(n²) when the pivot is always the smallest or largest (try Already sorted!).

Try this in the 3D model

  • Watch the pink pivot step forward, then watch cyan (≤ pivot) and purple (> pivot) regions grow.
  • After each partition, notice that the pivot turns green and never moves again.
  • Load Already sorted and play it. Count the comparisons — why is it so slow here?

The idea

Quick sort is another divide-and-conquer algorithm, but it does the hard work before recursing instead of after:

  1. Pick a pivot — here, the last element.
  2. Partition: rearrange the array so everything ≤ pivot is on its left and everything > pivot is on its right. The pivot is now in its final position.
  3. Recurse on the left part and the right part.

No merging is needed — when the recursion finishes, the array is sorted.

Analogy: a teacher sorting students by height picks one student (the pivot) and says “shorter than her, stand on the left; taller, on the right”. She is now in exactly the right spot. Repeat inside each group.

Lomuto partition, step by step

We scan with j from lo to hi − 1, and i marks the end of the “≤ pivot” zone:

pivot = a[hi]
i = lo - 1
for j in lo .. hi-1:
    if a[j] <= pivot:
        i += 1
        swap(a[i], a[j])        # grow the ≤ zone
swap(a[i+1], a[hi])             # put the pivot between the zones
return i + 1                    # the pivot's final index

At every moment the range looks like this:

lo … i i+1 … j−1 j … hi−1 hi
≤ pivot (cyan) > pivot (purple) not checked yet pivot (pink)

In the 3D model the pivot steps forward out of the row while the partition happens, and drops back into its final slot at the end.

Why is it fast — and when isn’t it?

If the pivot splits the array roughly in half each time, there are about log₂ n levels of recursion, each doing O(n) work in total → O(n log n).

But if the pivot is always the smallest or largest element, one side gets everything: n levels of O(n) → O(n²). With “last element as pivot”, this happens on already sorted data — try it in the model!

Fixes used in practice:

  • Random pivot — swap a random element into the pivot position first.
  • Median-of-three — use the median of the first, middle and last elements.
  • Introsort (C++ std::sort) — switch to heap sort if the recursion gets too deep.

Even so, quick sort is often the fastest sort in practice: it works in-place and its inner loop is very cache-friendly.

Code

def quick_sort(a, lo=0, hi=None):
    if hi is None:
        hi = len(a) - 1
    if lo < hi:
        p = partition(a, lo, hi)
        quick_sort(a, lo, p - 1)
        quick_sort(a, p + 1, hi)
    return a

def partition(a, lo, hi):
    pivot = a[hi]
    i = 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

print(quick_sort([10, 80, 30, 90, 40, 50, 70]))   # [10, 30, 40, 50, 70, 80, 90]
#include <iostream>
#include <vector>
#include <utility>
using namespace std;

int partition(vector<int>& a, int lo, int hi) {
    int pivot = a[hi], i = lo - 1;
    for (int j = lo; j < hi; j++)
        if (a[j] <= pivot) swap(a[++i], a[j]);
    swap(a[i + 1], a[hi]);
    return i + 1;
}

void quickSort(vector<int>& a, int lo, int hi) {
    if (lo >= hi) return;
    int p = partition(a, lo, hi);
    quickSort(a, lo, p - 1);
    quickSort(a, p + 1, hi);
}

int main() {
    vector<int> a = {10, 80, 30, 90, 40, 50, 70};
    quickSort(a, 0, a.size() - 1);
    for (int x : a) cout << x << " ";   // 10 30 40 50 70 80 90
}

Quick sort vs merge sort

Quick sort Merge sort
Average time O(n log n) O(n log n)
Worst time O(n²) O(n log n)
Extra space O(log n) stack O(n) array
Stable ❌ No ✅ Yes
Typical speed Usually faster (in-place, cache-friendly) Predictable

Common mistakes

  • Recursing on (lo, p) instead of (lo, p − 1) — the pivot is already placed, and including it can loop forever.
  • Forgetting the final swap that moves the pivot into place.
  • Assuming O(n log n) always — remember the sorted-input trap.

Complexity at a glance

Case / operationTimeWhy
Best caseO(n log n)The pivot splits the array into two equal halves.
Average caseO(n log n)Random data gives reasonably balanced splits.
Worst caseO(n²)The pivot is always the smallest or largest (e.g. sorted input with a last-element pivot).
Extra spaceO(log n)

Quick check

Test yourself — pick an answer to see if you got it.

1. After one partition step, what is true about the pivot?

2. When does quick sort with the last element as pivot hit its worst case?

3. How do real libraries usually avoid the worst case?

4. Is quick sort in-place?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Quick Sort. Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.