AlgoViz

Quick sort

medium 18 min

Quick sort picks a pivot, partitions the array so smaller values sit to its left and larger values to its right, and then sorts each side the same way.

Video lesson · Chapter 1 of 6

The pivot book

0:00 / 5:01

Quicksort — Zia’s pivot crate

1:42Reel

Read caption

Porter Zia partitions five cargo crates around weight 4, placing it permanently before sorting the two smaller ranges. Partition once. Sort each side.

How it works

Step through the idea, or press Play.

Step 1 of 3

Choose a pivot. Pick one value as the reference: the last, the middle, a random one or the median of three

Understand it

Start here

What quick sort is

Quick sort is a divide-and-conquer sorting algorithm. Think of a class lining up by height: pick one student as the reference (the pivot), have everyone shorter stand on their left and everyone taller on their right, then repeat inside each group. The reference student is already standing exactly where they belong.

  • Choose pivot

    Select one value as the reference. Commonly the last, the first, the middle or a random value.

  • Partition

    Rearrange in place: smaller values to the left of the pivot, larger values to the right.

  • Recurse

    Apply the same process to the left part and the right part until every part has at most one value.

PPSR: the four beats of quick sort
  1. 1PickChoose a pivot
  2. 2PartitionSmaller left, larger right
  3. 3SortThe left part, recursively
  4. 4RecurseOn the right part too

Pick, Partition, Sort left, Recurse right. The pivot is placed during Partition, so there is nothing to combine at the end.

The algorithm

Divide, conquer, nothing to combine

quick_sort(arr, low, high)

All the work happens in partition, before the recursive calls. Merge sort is the mirror image: it splits for free and does its work while merging on the way back up.
Python
def quick_sort(arr, low=0, high=None):    if high is None:        high = len(arr) - 1    if low < high:        p = partition(arr, low, high)   # pivot is final at p        quick_sort(arr, low, p - 1)     # left of the pivot        quick_sort(arr, p + 1, high)    # right of the pivot    return arrdef partition(arr, low, high):    pivot = arr[high]                   # last value is the pivot    i = low - 1                         # end of the "< pivot" zone    for j in range(low, high):        if arr[j] < pivot:            i += 1            arr[i], arr[j] = arr[j], arr[i]    arr[i + 1], arr[high] = arr[high], arr[i + 1]    return i + 1print(quick_sort([8, 3, 7, 4, 9, 2, 6, 5]))# [2, 3, 4, 5, 6, 7, 8, 9]
Quick sort with the Lomuto partition, as in the visualizer. It sorts the list in place.
Edit and run it in your browser

Partitioning

The Lomuto scheme

Lomuto's partition uses the last value as the pivot and two indexes: j scans every other value from left to right, and i marks the end of the zone of values smaller than the pivot. Whenever j finds a smaller value, the zone grows by one and that value is swapped into it. At the end the pivot is swapped into the slot just after the zone, i + 1.

Lomuto partition loop

The scan always makes exactly n−1n - 1 comparisons for a range of nn values, whatever the data looks like.

Loop invariant of Lomuto

arr[low..i]⏟< pivot  ∣  arr[i+1..j−1]⏟≥ pivot  ∣  arr[j..high−1]⏟not seen yet  ∣  pivot\underbrace{\text{arr}[\text{low}..i]}_{< \text{ pivot}} \;\Big|\; \underbrace{\text{arr}[i+1..j-1]}_{\ge \text{ pivot}} \;\Big|\; \underbrace{\text{arr}[j..\text{high}-1]}_{\text{not seen yet}} \;\Big|\; \text{pivot}
Before every step of the scan the range splits into these four parts. When jj reaches high the third part is empty, so swapping the pivot to i+1i + 1 leaves smaller values on its left and the rest on its right.
jarr[j]<5< 5 ?ActionArray after
08noskip8, 3, 7, 4, 9, 2, 6, 5
13yesi = 0, swap 0 and 13, 8, 7, 4, 9, 2, 6, 5
27noskip3, 8, 7, 4, 9, 2, 6, 5
34yesi = 1, swap 1 and 33, 4, 7, 8, 9, 2, 6, 5
49noskip3, 4, 7, 8, 9, 2, 6, 5
52yesi = 2, swap 2 and 53, 4, 2, 8, 9, 7, 6, 5
66noskip3, 4, 2, 8, 9, 7, 6, 5
endswap pivot into i + 1 = 33, 4, 2, 5, 9, 7, 6, 8
Partitioning [8, 3, 7, 4, 9, 2, 6, 5] around 5: 7 comparisons, 3 swaps plus the pivot swap. 5 is now at index 3, its sorted position.

Worked example

Sorting [8, 3, 7, 4, 9, 2, 6, 5]

Call (low, high)SubarrayPivotAfter partitionPivot lands at
(0, 7)8, 3, 7, 4, 9, 2, 6, 553, 4, 2, 5, 9, 7, 6, 83
(0, 2)3, 4, 222, 4, 30
(1, 2)4, 333, 41
(4, 7)9, 7, 6, 887, 6, 8, 96
(4, 5)7, 666, 74
Five partitions and 7+2+1+3+1=147 + 2 + 1 + 3 + 1 = 14 comparisons. Calls on one value, such as (2, 2) and (7, 7), stop at the base case. Result: [2, 3, 4, 5, 6, 7, 8, 9].

The recursion tree

Three levels of partitioning for 8 values, close to log⁡28=3\log_2 8 = 3. Each level touches at most nn values, which is the whole intuition behind O(nlog⁡n)O(n \log n).

Partitioning

The Hoare scheme

Tony Hoare's original 1961 partition walks two pointers towards each other. i moves right until it finds a value ≥\ge pivot, j moves left until it finds a value ≤\le pivot, and the pair is swapped because both are on the wrong side. When the pointers cross, j is the split point: every value in [low..j] is ≤\le pivot and every value in [j+1..high] is ≥\ge pivot.

Hoare partition loop

Each swap fixes two misplaced values at once. On [8, 3, 7, 4, 9, 2, 6, 5] with pivot 4, Hoare needs 2 swaps where Lomuto needs 4.
Python
def hoare_partition(arr, low, high):    pivot = arr[(low + high) // 2]    i, j = low - 1, high + 1    while True:        i += 1        while arr[i] < pivot:            i += 1        j -= 1        while arr[j] > pivot:            j -= 1        if i >= j:            return j        arr[i], arr[j] = arr[j], arr[i]def quick_sort_hoare(arr, low=0, high=None):    if high is None:        high = len(arr) - 1    if low < high:        p = hoare_partition(arr, low, high)        quick_sort_hoare(arr, low, p)        quick_sort_hoare(arr, p + 1, high)    return arrprint(quick_sort_hoare([8, 3, 7, 4, 9, 2, 6, 5]))   # [2, 3, 4, 5, 6, 7, 8, 9]print(quick_sort_hoare([5, 5, 5, 5, 5, 5]))         # equal values split evenly
Hoare partition. The recursive calls use (low, p) and (p + 1, high) because the pivot is not fixed in place.
Edit and run it in your browser
LomutoHoare
Pointersboth move right (ii trails jj)move towards each other
Pivotlast valueusually the middle value
Pivot after partitionin its final slot at ppsomewhere in the range, not fixed
Recursive calls(low, p - 1) and (p + 1, high)(low, p) and (p + 1, high)
Swaps on random dataabout n2\frac{n}{2}about n6\frac{n}{6}, three times fewer
All values equal0∣n−10 \mid n-1 split: O(n2)O(n^2)even split: O(nlog⁡n)O(n \log n)
Ease of writingsimpler, popular in teachingtrickier boundaries
Lomuto is easier to get right; Hoare is faster in practice. Production libraries use refinements of Hoare or three-way partitioning.

Complexity

Best case: O(n log n)

The best case is when every pivot is the median of its range, so each partition splits nn values into two halves. Partitioning a range of nn values costs n−1n - 1 comparisons, and then two problems of half the size remain.

Best-case recurrence

T(n)=2 T ⁣(n2)+(n−1),T(1)=0T(n) = 2\,T\!\left(\frac{n}{2}\right) + (n - 1), \qquad T(1) = 0
The same shape as merge sort's recurrence. Case 2 of the master theorem gives Θ(nlog⁡n)\Theta(n \log n) straight away.

Unrolling it level by level

T(n)=∑k=0log⁡2n−12k(n2k−1)=nlog⁡2n−(n−1)=O(nlog⁡n)T(n) = \sum_{k=0}^{\log_2 n - 1} 2^k \left(\frac{n}{2^k} - 1\right) = n\log_2 n - (n - 1) = O(n \log n)
Level kk has 2k2^k ranges of size n2k\frac{n}{2^k}, so it costs just under nn comparisons, and there are log⁡2n\log_2 n levels. For n=8n = 8: 8⋅3−7=178 \cdot 3 - 7 = 17 comparisons at most.
nlevels log⁡2n\log_2 nbest case about nlog⁡2nn \log_2 nworst case n(n−1)2\frac{n(n-1)}{2}
832428
6463842,016
1,0241010,240523,776
1,000,000about 20about 20 millionabout 500 billion
At n=64n = 64 the old rule of thumb compares nlog⁡n=384n \log n = 384 with n2=4096n^2 = 4096; the exact worst case is 2,016 comparisons, still more than five times worse, and the gap explodes as nn grows.

Complexity

Worst case: O(n²)

The worst case is when every pivot is the smallest or largest value of its range. The partition then peels off just the pivot and leaves n−1n - 1 values on one side. With a last-value pivot this happens on sorted, reversed and nearly sorted input, the inputs people most often feed in.

Worst-case recurrence

T(n)=T(n−1)+(n−1)=(n−1)+(n−2)+⋯+1=n(n−1)2=O(n2)T(n) = T(n - 1) + (n - 1) = (n-1) + (n-2) + \dots + 1 = \frac{n(n-1)}{2} = O(n^2)
An arithmetic series. Reversed [7, 6, 5, 4, 3, 2, 1] costs 6+5+4+3+2+1=216 + 5 + 4 + 3 + 2 + 1 = 21 comparisons, and the recursion goes 7 levels deep instead of 3.

Balanced versus lopsided splits

The number of comparisons per level is the same either way. What changes is the number of levels.

Complexity

Average case: still O(n log n)

Why is the average close to the best case and not the worst? Because a split does not need to be perfect, only not terrible. Even a fixed 1 : 9 split every time keeps the depth logarithmic.

A lopsided but constant split is fine

T(n)=T ⁣(n10)+T ⁣(9n10)+cn  ⇒  depth=log⁡10/9n≈6.6 log⁡2n  ⇒  O(nlog⁡n)T(n) = T\!\left(\frac{n}{10}\right) + T\!\left(\frac{9n}{10}\right) + cn \;\Rightarrow\; \text{depth} = \log_{10/9} n \approx 6.6\,\log_2 n \;\Rightarrow\; O(n \log n)
Every level still costs at most cncn, and there are O(log⁡n)O(\log n) levels. Only splits that leave a constant number of values on one side, like 0∣n−10 \mid n-1, push it to quadratic.

Expected comparisons with a random pivot

C(n)=(n−1)+1n∑k=0n−1[C(k)+C(n−1−k)]=(n−1)+2n∑k=0n−1C(k)C(n) = (n - 1) + \frac{1}{n}\sum_{k=0}^{n-1}\big[C(k) + C(n-1-k)\big] = (n - 1) + \frac{2}{n}\sum_{k=0}^{n-1} C(k)
The pivot is equally likely to land at any rank kk, leaving kk values on the left and n−1−kn - 1 - k on the right. Average the cost over all nn ranks.

Solving the recurrence

C(n)=2(n+1)Hn−4n≈2nln⁡n≈1.39 nlog⁡2n,Hn=1+12+⋯+1nC(n) = 2(n+1)H_n - 4n \approx 2n \ln n \approx 1.39\, n \log_2 n, \qquad H_n = 1 + \tfrac12 + \dots + \tfrac1n
Only about 39% more comparisons than the perfect best case. Another way to see it: values of ranks i<ji < j are compared only if one of them is the first pivot chosen among ranks i..ji..j, which has probability 2j−i+1\frac{2}{j - i + 1}; summing over all pairs gives the same 2nln⁡n2n \ln n.

Memory and order

O(log n) space, and not stable

Stack space

Sbest(n)=O(log⁡n),Sworst(n)=O(n),Ssmaller side first(n)≤log⁡2nS_{\text{best}}(n) = O(\log n), \qquad S_{\text{worst}}(n) = O(n), \qquad S_{\text{smaller side first}}(n) \le \log_2 n
Partitioning is in place, so the only extra memory is the recursion stack. Recursing into the smaller part and looping on the larger one guarantees each frame handles at most half the values of the one before, so the depth never exceeds log⁡2n\log_2 n.
Python
def quick_sort(arr, low=0, high=None):    if high is None:        high = len(arr) - 1    while low < high:        p = partition(arr, low, high)        if p - low < high - p:            quick_sort(arr, low, p - 1)    # smaller side: recurse            low = p + 1                    # larger side: loop        else:            quick_sort(arr, p + 1, high)            high = p - 1    return arrdef partition(arr, low, high):    pivot, i = arr[high], low - 1    for j in range(low, high):        if arr[j] < pivot:            i += 1            arr[i], arr[j] = arr[j], arr[i]    arr[i + 1], arr[high] = arr[high], arr[i + 1]    return i + 1print(quick_sort(list(range(3000))) == list(range(3000)))   # True, no RecursionError
Smaller side first: the stack stays O(log n) even when splits are bad (the time can still be O(n²)).
Edit and run it in your browser

Pivot choice

Choosing a good pivot

  • Last (or first) value

    Simplest to code, fine for teaching. Degrades to O(n2)O(n^2) on sorted and reversed input.

  • Random value

    Swap a random value to the end first. No input is bad on purpose: expected O(nlog⁡n)O(n \log n) for every input. A good default in production.

  • Median of three

    Take the median of the first, middle and last values. Cheap, and it turns sorted input into the best case.

  • Middle value

    Simple and works well on nearly sorted data, but crafted inputs can still defeat it.

Which pivot strategy?

Introsort (used by C++ std::sort) watches the recursion depth and falls back to heap sort past about 2log⁡2n2 \log_2 n levels, which caps the worst case at O(nlog⁡n)O(n \log n).
Input (n = 7)Last-value pivotMedian of three
Random [8, 3, 7, ...] styleabout nlog⁡nn \log nabout nlog⁡nn \log n
Sorted [1, 2, 3, 4, 5, 6, 7]21 comparisons10 comparisons
Reversed [7, 6, 5, 4, 3, 2, 1]21 comparisons10 comparisons
Nearly sorted [1, 2, 4, 3, 5, 6, 7]19 comparisons11 comparisons
The worst case comes from the pivot rule meeting a particular input, not from the input alone.

Head to head

Quick sort vs merge sort vs heap sort

PropertyQuick sortMerge sortHeap sort
Best timeO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)
Average timeO(nlog⁡n)O(n \log n), about 1.39 nlog⁡2n1.39\,n \log_2 n comparisonsO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)
Worst timeO(n2)O(n^2)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)
Extra spaceO(log⁡n)O(\log n) stackO(n)O(n) bufferO(1)O(1)
StableNoYesNo
In placeYesNo (for arrays)Yes
Cache behaviourExcellent: sequential scansGoodPoor: jumps around the heap
Pivot mattersCriticalNot applicableNot applicable
Quick sort usually wins on arrays in memory thanks to tight inner loops and sequential access; merge sort wins when stability or a guarantee is needed; heap sort when memory is tight and a guarantee is needed.

Good for

  • Arrays, where random access makes swaps cheap.
  • Large in-memory datasets with a good pivot rule.
  • When average O(nlog⁡n)O(n \log n) is acceptable and speed matters.
  • Memory-constrained code: it sorts in place.
  • General-purpose sorting of numbers, and selection problems via quickselect.

Avoid when

  • Data may be sorted and the pivot is naive: use a random pivot, or insertion sort for nearly sorted data.
  • A guaranteed O(nlog⁡n)O(n \log n) worst case is required: use merge sort or heap sort.
  • Stability is required: quick sort is not stable.
  • Sorting a linked list: no random access, so merge sort is the natural fit.
  • Tiny arrays: insertion sort has less overhead below a few dozen values.

Recap

Key takeaways

Key points

  • Quick sort picks a pivot, partitions smaller values left and larger values right, and recurses on both sides; the pivot ends in its final slot.
  • Lomuto: last-value pivot, n−1n - 1 comparisons per partition, recurse on (low,p−1)(low, p-1) and (p+1,high)(p+1, high). Hoare: two inward pointers, fewer swaps, recurse on (low,p)(low, p) and (p+1,high)(p+1, high).
  • Best case T(n)=2T(n/2)+n−1=O(nlog⁡n)T(n) = 2T(n/2) + n - 1 = O(n \log n); worst case T(n)=T(n−1)+n−1=n(n−1)2T(n) = T(n-1) + n - 1 = \frac{n(n-1)}{2}; average about 1.39 nlog⁡2n1.39\, n \log_2 n.
  • The worst case comes from always picking the min or max, as a last-value pivot does on sorted input. Random or median-of-three pivots fix it.
  • In place with O(log⁡n)O(\log n) stack on average (O(n)O(n) worst, ≤log⁡2n\le \log_2 n with smaller side first). Not stable.
  • Real libraries combine it: introsort switches to heap sort when recursion gets deep and to insertion sort for small ranges.

Sources