# quicksort

> pick a pivot, partition around it, sort each side.

source: https://learning.anthnydas.com/algos/quicksort/

## tl;dr

pick a pivot. move everything below it to its left and everything else to its right, and it's in its final place. then sort the two sides the same way.

- **average:** O(n log n) (about 1.39 n log₂ n comparisons)
- **worst:** O(n²) (a pivot at one end, every time)
- **space:** O(log n) (the stack, recursing on the smaller side)
- **stable:** no (a partition swaps equal items past each other)
- **in place:** yes (swaps only, no buffer)
- **reach for it:** the usual in-memory sort, what go's, rust's and java's unstable sorts are built on, quickselect, the kth smallest without sorting the rest, partitioning, the small ones first in one pass

quicksort picks one item, the pivot, and puts it where it belongs: everything below it on its left, everything else on its right. that one pass is the partition. the pivot never moves again, and the two sides are smaller copies of the same problem. c. a. r. hoare published it in 1961,[^hoare] and the unstable sorts in go, rust and java are still built on it.

## the idea

> **interactive figure:** an animation in six steps. eight numbers, 34, 12, 51, 23, 29, 8, 45 and 17, drawn as bars. the middle one, 29, turns white as the pivot and swaps to the end. two pointers start at the front: i in cyan and j in amber. j walks right: 34 stays, 12 swaps forward to i, 51 stays, 23 swaps forward, 17 swaps forward, 8 swaps forward, 45 stays, and i ends at index 4. a counter under the bars reaches 7 comparisons. the pivot swaps into index 4, with 12, 23, 17 and 8 on its left in cyan and 34, 45 and 51 on its right, 51 still white from the swap. each side is sorted the same way, faster, and the bars end as 8, 12, 17, 23, 29, 34, 45, 51, all in solid cyan, after 13 comparisons.

eight numbers, in no particular order. the middle one, 29, is the pivot: the item every other one gets compared with.

the pivot swaps to the end, out of the way. two pointers start at the front: i marks where the next small item goes, and j walks the array.

j looks at each item once. 34 isn't below 29, so it stays. 12 is, so it swaps forward to i, and i moves up. 51 stays. 23, 17 and 8 each swap forward. four items are below the pivot, so i stops at 4.

the pivot swaps into slot i. everything left of 29 is smaller, everything right of it is bigger: 29 is in its final place, after 7 comparisons.

each side is a smaller quicksort. the right side, 34, 45, 51, has three items and gets the recursive call. the left, 12, 23, 17, 8, waits for the loop.

4 partitions and 13 comparisons later, the array is sorted: 8, 12, 17, 23, 29, 34, 45, 51. every item was a pivot once, or ended up in a range of one.

## watch it run

step through a run. the bracket is the range being partitioned. the pivot is white with a dashed ring, items below it turn cyan and the rest amber, i is cyan and j is amber under the bars, and an item in its final place turns solid cyan. the pseudocode follows along, with counts of the comparisons, the swaps, how deep the partitions nest, and how many quicksort calls are on the stack.

> **interactive figure:** an interactive stepper: bars for 8, 12, 16 or 32 items, random, sorted, reversed or all equal, with a pivot rule to pick: the middle item, the last item, a random item, or the median of three. each step shows the range being partitioned under a bracket, the pivot white with a dashed ring, the items below it cyan and the rest amber, i in cyan and j in amber under the bars, items in their final place in solid cyan, the matching pseudocode line highlighted, and counts of the comparisons, the swaps, the depth of the partition, the quicksort calls on the stack and the step. with the middle item as pivot, 8 sorted items take 13 comparisons and 3 levels; with the last item they take 28 comparisons and 7 levels, and 32 sorted items take 496 comparisons and 31 levels.

pick sorted input and the last item as pivot: every pivot is the biggest in its range, every right side is empty, and 32 items take 496 comparisons and 31 levels, one per item. switch to the middle item and the same input nests 5 levels deep, log₂ 32. then try all-equal input: with every rule the pivot lands at the front of its range, and 32 items take 496 comparisons with the middle item too.

## try it

the partition is the whole trick. predict what it does.

> **interactive figure:** a practice exercise on a row of 5 to 8 numbers with their indexes under them and the middle item marked as the pivot. two kinds of question are answered by tapping the row: which index the pivot lands at, and which item ends up at index 0 after the partition. two by buttons: how many comparisons one partition makes, and, with the partitioned row shown, which two ranges get sorted next.

## pseudocode

```text
quicksort(a, lo, hi):  # sorts a[lo:hi]
  while hi - lo > 1:  # 0 or 1 items: sorted
    p = partition(a, lo, hi)  # the pivot is placed
    if p - lo < hi - p - 1:  # left side smaller
      quicksort(a, lo, p)  # recurse on it,
      lo = p + 1  # loop on the bigger one
    else:
      quicksort(a, p + 1, hi)
      hi = p

partition(a, lo, hi):  # lomuto
  mid = lo + (hi - lo) // 2  # the pivot
  swap a[mid], a[hi - 1]  # park it at the end
  pivot = a[hi - 1]
  i = lo  # a[lo:i] below the pivot, a[i:j] not
  for j in range(lo, hi - 1):
    if a[j] < pivot:
      swap a[i], a[j]
      i += 1
  swap a[i], a[hi - 1]  # the pivot lands at i
  return i
```

ranges are half-open: `a[lo:hi]` is `lo` up to but not including `hi`, and `//` is integer division. the pivot is the middle item, parked at `hi - 1` while `j` walks the rest. ties go right: `a[j] < pivot` is strict, so an item equal to the pivot stays on the not-below side. the loop recurses on the smaller side and goes round again for the bigger one. that's what keeps the stack short.

## the partition, up close

> **interactive figure:** a still figure of the page's example in the middle of its first partition, just after j has passed 23: the bars 12, 23, 51, 34, 17, 8, 45, 29. the pivot, 29, is parked at the end in white with a dashed ring. 12 and 23, left of i, are cyan: below the pivot. 51 and 34, from i up to j, are amber: not below it. 17, under j, has a white ring: the item being looked at. 8 and 45 are plain: not seen yet. a legend under the bars says the same.

- **the invariant.** at every step, everything in `[lo, i)` is below the pivot, everything in `[i, j)` is not, and `[j, hi - 1)` hasn't been looked at. the pivot sits at `hi - 1`, out of the way
- **one step.** `j` looks at one item. if it isn't below the pivot, `j` moves on and the not-below stretch is one longer. if it is, it swaps with `a[i]`, the first not-below item, which goes to the end of its stretch, and `i` moves up. both stretches grow in place. nothing shifts
- **the end.** `j` reaches the pivot. `a[i]` is the first item that isn't below it, so the pivot swaps in there: smaller on its left, the rest on its right, and it's done for good. when nothing was below it, `i` is still `lo`, and it lands at the front of the range
- **the cost.** a range of k items takes k - 1 comparisons, one per item but the pivot, and at most k + 1 swaps: one per item below the pivot, and two to park and place the pivot
- **what it does to order.** the items below the pivot keep their order, since each one swaps into the next slot from the front. the others get rotated as they're swapped out of the way, and that's where stability goes: two equal keys can trade places. 1a, 1b, 0c comes out as 0c, 1b, 1a

## complexity

a partition of k items costs k - 1 comparisons, so a level of the recursion costs at most n. the best case is a pivot that splits its range in half every time: log₂ n levels, so about n log₂ n comparisons. on random input with distinct keys the average is 2n ln n comparisons, about 1.39 n log₂ n.[^algs4] the worst case is a pivot at one end of its range every time: the sides are n - 1 and 0, there are n - 1 levels, and the comparisons add up to n(n - 1) / 2. the space is the stack, O(log n) with the smaller side recursing.

> **interactive figure:** a line chart of comparisons against the number of items, from 16 to 4,096 on a doubling scale, for insertion sort, merge sort, quicksort and heap sort on the same arrays, quicksort in cyan, with a switch between shuffled, already sorted and reversed input. shuffled: at 1,024 items quicksort makes 11,185 comparisons, merge sort 8,962, heap sort 17,273 and insertion sort 273,132, off the top of the chart; at 4,096, quicksort 59,922, merge sort 43,932 and heap sort 85,650. already sorted: at 1,024, quicksort 8,204, merge sort 5,120, heap sort 18,060 and insertion sort 1,023. reversed: quicksort 8,601, merge sort 5,120, heap sort 16,407 and insertion sort 523,776.

on the chart's shuffled arrays, quicksort makes 11,185 comparisons at 1,024 items and 59,922 at 4,096: more than merge sort's 8,962 and 43,932, since merge sort's halves are always equal and a partition's sides rarely are, and fewer than heap sort's 17,273 and 85,650. the middle item as pivot is what keeps sorted and reversed input in the same band, 8,204 and 8,601 comparisons at 1,024, where insertion sort swings from 1,023 to 523,776.

what the chart can't show is the pivot rule. with the last item as pivot, sorted input is the worst case: 8,386,560 comparisons at 4,096, n(n - 1) / 2, against 40,974 with the middle item. all-equal input is as bad with every rule, since nothing is ever below the pivot and it lands at the front of its range every time: 8,386,560 with the middle, last or random item, and 8,394,750 with the median of three, which pays two comparisons per partition to pick it. on 4,096 shuffled numbers the rules are close: 59,922 comparisons with the middle item, 57,551 with a random one, 53,992 with the median of three.

> **interactive figure:** a line chart of how deep the partitions nest against the number of items, from 16 to 4,096 on a doubling scale, with a pivot rule to pick: the middle item, the last item, a random item, or the median of three. solid lines for random input, sorted input and all-equal input, dashed lines for the calls on the stack with random and with sorted input, and a dotted log₂ n. with the middle item, sorted input nests exactly log₂ n deep, 4 at 16 and 12 at 4,096, on a stack of 11, and random input nests 5 deep at 16 and 27 at 4,096, on a stack of 7. with the last item, sorted input and all-equal input climb off the chart on their way to 4,095 levels at 4,096, while the stack for sorted input stays at 1. every stack line stays under the log₂ n line.

how deep the partitions nest is one thing, the stack another. recursing on both sides puts a frame on the stack for every level, n - 1 of them in the worst case. recursing on the smaller side only, and looping on the bigger one, keeps the stack at log₂ n frames at most: the smaller side is less than half its range, so each frame on the stack halves the problem. on 1,024 sorted items with the last item as pivot, the partitions nest 1,023 deep and the stack never holds more than one call. on 4,096 shuffled items with the middle item, they nest 27 deep on a stack of 7.

## implementations

each tab is the real file from the repo, checked by its tests (`go test`, `cargo test`, `vitest`, `make test`, `swift test`, `python -m unittest`), including 2000 seeded arrays against the language's own sort, 100,000 sorted items, which is quick with the middle pivot, and 100 equal items, where the pivot lands at the front every time. every tab picks the middle item, parks it at the end, partitions with lomuto's scheme with ties to the right, and recurses on the smaller side only, so the tabs make the same swaps in the same order, and every tab exposes its partition, since the tests call it. typescript takes a comparator, so its tests can count: 1,468,946 comparisons for the 100,000 sorted items, and 4,950 for the 100 equal ones.

`go/algos/quicksort/quicksort.go`

```go
// Package quicksort is a reference quicksort, in place. each round picks the middle item of the range as
// the pivot, partitions the range around it, and sorts the two sides: the smaller one with a recursive
// call, the bigger one by going round the loop again, so the stack never holds more than log2 n calls,
// whatever the input. O(n log n) on average, O(n²) at worst, and not stable: a partition can swap equal
// items past each other.
package quicksort

// Sort sorts a in ascending order.
func Sort(a []int) {
	sortRange(a, 0, len(a))
}

// sortRange sorts a[lo:hi]: it partitions the range, recurses on the smaller side and loops on the bigger.
func sortRange(a []int, lo, hi int) {
	for hi-lo > 1 {
		p := Partition(a, lo, hi) // the pivot is at p for good
		if p-lo < hi-p-1 {
			sortRange(a, lo, p) // the left side is smaller: recurse on it
			lo = p + 1          // and loop on the right
		} else {
			sortRange(a, p+1, hi)
			hi = p
		}
	}
}

// Partition runs Lomuto's partition on a[lo:hi], which holds at least one item, around its middle item.
// The pivot is parked at the end, then j walks the rest: every item below the pivot swaps forward to i, so
// a[lo:i] is below the pivot and a[i:j] is not. At the end the pivot swaps into slot i, its final place.
// It returns i.
func Partition(a []int, lo, hi int) int {
	mid := lo + (hi-lo)/2
	a[mid], a[hi-1] = a[hi-1], a[mid]
	pivot := a[hi-1]
	i := lo
	for j := lo; j < hi-1; j++ {
		if a[j] < pivot { // strictly below: ties go right
			a[i], a[j] = a[j], a[i]
			i++
		}
	}
	a[i], a[hi-1] = a[hi-1], a[i]
	return i
}
```

`rust/algos/src/quicksort.rs`

```rust
//! quicksort, in place. each round picks the middle item of the range as the pivot, partitions the range around it, and sorts the two sides: the smaller one with a recursive call, the bigger one by going round the loop again, so the stack never holds more than log2 n calls, whatever the input. O(n log n) on average, O(n²) at worst, and not stable: a partition can swap equal items past each other.

/// Sorts `a` in ascending order, in place.
pub fn quicksort(a: &mut [i32]) {
    sort(a, 0, a.len());
}

/// Sorts `a[lo..hi]`.
fn sort(a: &mut [i32], mut lo: usize, mut hi: usize) {
    while hi - lo > 1 {
        let p = partition(a, lo, hi); // the pivot is at p for good
        if p - lo < hi - p - 1 {
            sort(a, lo, p); // the left side is smaller: recurse on it
            lo = p + 1; // and loop on the right
        } else {
            sort(a, p + 1, hi);
            hi = p;
        }
    }
}

/// Lomuto's partition of `a[lo..hi]`, which holds at least one item, around its middle item. The
/// pivot is parked at the end, then `j` walks the rest: every item below the pivot swaps forward
/// to `i`, so `a[lo..i]` is below the pivot and `a[i..j]` is not. At the end the pivot swaps into
/// slot `i`, its final place. Returns `i`.
pub fn partition(a: &mut [i32], lo: usize, hi: usize) -> usize {
    let mid = lo + (hi - lo) / 2;
    a.swap(mid, hi - 1);
    let pivot = a[hi - 1];
    let mut i = lo;
    for j in lo..hi - 1 {
        if a[j] < pivot {
            a.swap(i, j);
            i += 1;
        }
    }
    a.swap(i, hi - 1);
    i
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sorts_each_case() {
        let cases: [(&str, &[i32], &[i32]); 7] = [
            ("empty", &[], &[]),
            ("one item", &[5], &[5]),
            ("sorted", &[1, 2, 3, 4], &[1, 2, 3, 4]),
            ("reversed", &[4, 3, 2, 1], &[1, 2, 3, 4]),
            ("duplicates", &[3, 1, 3, 1], &[1, 1, 3, 3]),
            ("all equal", &[7, 7, 7], &[7, 7, 7]),
            (
                "the page's example",
                &[34, 12, 51, 23, 29, 8, 45, 17],
                &[8, 12, 17, 23, 29, 34, 45, 51],
            ),
        ];
        for (name, input, want) in cases {
            let mut a = input.to_vec();
            quicksort(&mut a);
            assert_eq!(a, want, "{name}");
        }
    }

    #[test]
    fn the_pages_example_one_partition_29_lands_at_4_with_the_smaller_items_before_it_in_their_old_order()
     {
        let mut a = [34, 12, 51, 23, 29, 8, 45, 17];
        assert_eq!(partition(&mut a, 0, 8), 4);
        assert_eq!(a, [12, 23, 17, 8, 29, 34, 45, 51]);
    }

    #[test]
    fn a_partition_of_a_sub_range_leaves_the_rest_alone() {
        let mut a = [9, 5, 1, 4, 2, 0];
        // a[1..5] is 5, 1, 4, 2: the pivot 4 is parked at index 4, 1 and 2 swap forward, and it
        // lands at 3
        assert_eq!(partition(&mut a, 1, 5), 3);
        assert_eq!(a, [9, 1, 2, 4, 5, 0]);
    }

    #[test]
    fn agrees_with_the_built_in_sort_on_2000_seeded_arrays() {
        // xorshift32 seeded with 42, like the other tests here
        let mut state: u32 = 42;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        };
        for round in 0..2000 {
            // values below 20 make plenty of ties, values below 1000 almost none
            let below = if round % 2 == 1 { 20 } else { 1000 };
            let mut a: Vec<i32> = (0..next() % 64).map(|_| (next() % below) as i32).collect();
            let mut want = a.clone();
            want.sort();
            quicksort(&mut a);
            assert_eq!(a, want);
        }
    }

    #[test]
    fn sorted_100000_items_and_as_many_reversed() {
        // the middle pivot halves them every time. the last item as pivot would compare
        // n(n - 1) / 2 times: 5 billion
        let want: Vec<i32> = (1..=100_000).collect();
        let mut a = want.clone();
        quicksort(&mut a);
        assert_eq!(a, want);
        let mut r: Vec<i32> = (1..=100_000).rev().collect();
        quicksort(&mut r);
        assert_eq!(r, want);
    }

    #[test]
    fn lomutos_weak_spot_partition_of_100_equal_items_returns_0_the_front() {
        let mut a = [7; 100];
        // nothing is below the pivot, so it lands at the front and the other 99 are all on one side
        assert_eq!(partition(&mut [7; 100], 0, 100), 0);
        quicksort(&mut a);
        assert_eq!(a, [7; 100]);
    }
}
```

`site/src/visuals/quicksort/quicksort.ts`

```ts
const ascending = <T>(a: T, b: T) => (a < b ? -1 : a > b ? 1 : 0);

/**
 * Quicksort, in place. Each round picks the middle item of the range as the pivot, partitions the range around
 * it, and sorts the two sides: the smaller one with a recursive call, the bigger one by going round the loop
 * again, so the stack never holds more than log2 n calls, whatever the input. O(n log n) on average, O(n²) at
 * worst, and not stable: a partition can swap equal items past each other.
 */
export function quicksort<T>(a: T[], compare: (a: T, b: T) => number = ascending): void {
  sort(a, 0, a.length, compare);
}

function sort<T>(a: T[], lo: number, hi: number, compare: (a: T, b: T) => number): void {
  while (hi - lo > 1) {
    const p = partition(a, lo, hi, compare); // the pivot is at p for good
    if (p - lo < hi - p - 1) {
      sort(a, lo, p, compare); // the left side is smaller: recurse on it
      lo = p + 1; // and loop on the right
    } else {
      sort(a, p + 1, hi, compare);
      hi = p;
    }
  }
}

/**
 * Lomuto's partition of a[lo:hi], which holds at least one item, around its middle item. The pivot is parked at
 * the end, then j walks the rest: every item below the pivot swaps forward to i, so a[lo:i] is below the pivot
 * and a[i:j] is not. At the end the pivot swaps into slot i, its final place. Returns i.
 */
export function partition<T>(
  a: T[],
  lo: number,
  hi: number,
  compare: (a: T, b: T) => number = ascending,
): number {
  const mid = lo + Math.floor((hi - lo) / 2);
  swap(a, mid, hi - 1);
  const pivot = a[hi - 1];
  let i = lo;
  for (let j = lo; j < hi - 1; j++) {
    if (compare(a[j], pivot) < 0) {
      swap(a, i, j);
      i++;
    }
  }
  swap(a, i, hi - 1);
  return i;
}

function swap<T>(a: T[], x: number, y: number): void {
  [a[x], a[y]] = [a[y], a[x]];
}
```

`c/algos/quicksort.c`

```c
/* quicksort, in place. each round picks the middle item of the range as the pivot, partitions the range around it, and sorts the two sides: the smaller one with a recursive call, the bigger one by going round the loop again, so the stack never holds more than log2 n calls, whatever the input. O(n log n) on average, O(n²) at worst, and not stable: a partition can swap equal items past each other. */
#include "quicksort.h"

static void swap(int *a, size_t x, size_t y) {
    int t = a[x];
    a[x] = a[y];
    a[y] = t;
}

/* the pivot is parked at the end, then j walks the rest: every item below the pivot swaps forward
   to i, so a[lo..i) is below the pivot and a[i..j) is not. at the end the pivot swaps into slot i,
   its final place */
size_t partition(int *a, size_t lo, size_t hi) {
    size_t mid = lo + (hi - lo) / 2;
    swap(a, mid, hi - 1); /* park the pivot at the end */
    int pivot = a[hi - 1];
    size_t i = lo;
    for (size_t j = lo; j < hi - 1; j++) {
        if (a[j] < pivot) { /* strictly below: ties go right */
            swap(a, i, j);
            i++;
        }
    }
    swap(a, i, hi - 1); /* the pivot lands in its final slot */
    return i;
}

/* sorts a[lo..hi). each recursive call gets the smaller side, at most half the range, so calls nest
   at most log2 n deep */
static void sort(int *a, size_t lo, size_t hi) {
    while (hi - lo > 1) {
        size_t p = partition(a, lo, hi); /* the pivot is at p for good */
        if (p - lo < hi - p - 1) {
            sort(a, lo, p); /* the left side is smaller: recurse on it */
            lo = p + 1; /* and loop on the right */
        } else {
            sort(a, p + 1, hi);
            hi = p;
        }
    }
}

void quicksort(int *a, size_t n) {
    sort(a, 0, n);
}
```

`swift/algos/Quicksort.swift`

```swift
/// quicksort, in place. each round picks the middle item of the range as the pivot, partitions the range around it, and sorts the two sides: the smaller one with a recursive call, the bigger one by going round the loop again, so the stack never holds more than log2 n calls, whatever the input. O(n log n) on average, O(n²) at worst, and not stable: a partition can swap equal items past each other.
public func quicksort(_ a: inout [Int]) {
    sort(&a, 0, a.count)
}

private func sort(_ a: inout [Int], _ lo: Int, _ hi: Int) {
    var lo = lo
    var hi = hi
    while hi - lo > 1 {
        let p = partition(&a, lo, hi) // the pivot is at p for good
        if p - lo < hi - p - 1 {
            sort(&a, lo, p) // the left side is smaller: recurse on it
            lo = p + 1 // and loop on the right
        } else {
            sort(&a, p + 1, hi)
            hi = p
        }
    }
}

/// lomuto's partition of a[lo..<hi], which holds at least one item, around its middle item. the pivot is parked at
/// the end, then j walks the rest: every item below the pivot swaps forward to i, so a[lo..<i] is below the pivot
/// and a[i..<j] is not. at the end the pivot swaps into slot i, its final place. returns i
public func partition(_ a: inout [Int], _ lo: Int, _ hi: Int) -> Int {
    let mid = lo + (hi - lo) / 2
    a.swapAt(mid, hi - 1)
    let pivot = a[hi - 1]
    var i = lo
    for j in lo..<hi - 1 {
        if a[j] < pivot {
            a.swapAt(i, j)
            i += 1
        }
    }
    a.swapAt(i, hi - 1)
    return i
}
```

`python/algos/quicksort.py`

```python
"""quicksort, in place. each round picks the middle item of the range as the pivot, partitions the range around it, and sorts the two sides: the smaller one with a recursive call, the bigger one by going round the loop again, so the stack never holds more than log2 n calls, whatever the input. O(n log n) on average, O(n²) at worst, and not stable: a partition can swap equal items past each other."""

from __future__ import annotations


def quicksort(a: list[int]) -> None:
    """Sort a in place, smallest first."""

    def sort(lo: int, hi: int) -> None:
        while hi - lo > 1:
            p = partition(a, lo, hi)  # the pivot is at p for good
            if p - lo < hi - p - 1:
                sort(lo, p)  # the left side is smaller: recurse on it
                lo = p + 1  # and loop on the right
            else:
                sort(p + 1, hi)
                hi = p

    sort(0, len(a))


def partition(a: list[int], lo: int, hi: int) -> int:
    """Run Lomuto's partition on a[lo:hi], which holds at least one item, around its middle item.

    The pivot is parked at the end, then j walks the rest: every item below the pivot swaps forward to i, so
    a[lo:i] is below the pivot and a[i:j] is not. At the end the pivot swaps into slot i, its final place.
    Return i.
    """
    mid = lo + (hi - lo) // 2
    a[mid], a[hi - 1] = a[hi - 1], a[mid]
    pivot = a[hi - 1]
    i = lo
    for j in range(lo, hi - 1):
        if a[j] < pivot:  # strictly below: ties go right
            a[i], a[j] = a[j], a[i]
            i += 1
    a[i], a[hi - 1] = a[hi - 1], a[i]
    return i
```

## pitfalls

- **a fixed pivot at one end.** the first or last item is the worst pick for sorted input, which is common. 100,000 sorted items would take 4,999,950,000 comparisons with the last item as pivot. the middle item takes 1,468,946
- **keeping the pivot in a side.** after the partition the pivot is placed. include it in a side, and a range of two can come back as the same range of two, forever. both sides leave it out: `[lo, p)` and `[p + 1, hi)`
- **equal keys.** lomuto's scheme sends every item equal to the pivot to one side, so a run of equal keys is the worst case whatever the pivot rule: 100 equal items take 4,950 comparisons. three-way partitioning fixes it
- **recursing on both sides.** the stack can reach n - 1 frames on bad input. recurse on the smaller side and loop on the bigger
- **off by one.** the pivot is parked at `hi - 1`, `j` stops before it, and `i` is where it lands. half-open ranges keep the arithmetic to `p` and `p + 1`
- **counting on stability.** equal keys can come out in a different order. [merge sort](/algos/merge-sort/) if the order of ties matters

## variants

- **hoare partition.** two pointers start at the ends and walk toward each other: one stops at an item that isn't below the pivot, the other at one that isn't above it, and they swap. it only moves items that are on the wrong side, where lomuto's scheme swaps every item below the pivot, and it splits a run of equal keys between the sides. but the pass doesn't place the pivot, and the stopping rules are easy to get wrong. sedgewick and wayne's quicksort partitions this way, and stops both scans on keys equal to the pivot, which they call crucial to avoiding quadratic time[^algs4]
- **three-way partition.** below, equal and above, in one pass: dijkstra's dutch national flag problem. every key equal to the pivot is placed at once, so a run of them costs one partition instead of one per item, and with few distinct keys the sort is linear. sedgewick and wayne's quick3way does this, and they call it entropy-optimal[^algs4]. rust's sort handles equal keys a related way: when a pivot equals the one before it, the range is split into equal and greater, and the expected time is O(n log k) for k distinct keys[^rust]
- **random or sampled pivots.** a random pivot makes the worst case a matter of luck instead of input. the median of three gets most of the gain of sampling[^algs4]. go takes the median of three below 50 items and tukey's ninther from 50 up[^go]; rust's pivot is a recursive median of three, built to approximate a median of √n items[^rust]
- **introsort.** quicksort with a depth limit: when the partitions nest too deep, the range goes to heap sort, so the worst case is n log n. the name is musser's, from 1997.[^musser] go switches after `bits.Len(n)` bad partitions, rust after 2 log₂ n, java when its depth counter passes 384[^go][^rust][^java]
- **dual-pivot quicksort.** two pivots split the range in three. java's `Arrays.sort` for primitives is yaroslavskiy, bentley and bloch's version[^java]
- **pattern-defeating quicksort.** notices sorted and reversed ranges and runs of equal keys, scrambles a few items after an unbalanced partition, and falls back to heap sort. go's sort is one, after orson peters' pdqsort[^go]
- **small ranges to insertion sort.** below a cutoff a simpler sort wins. go switches at 12 items or fewer, rust at 20 or fewer, java under 44[^go][^rust][^java]
- **quickselect.** partition, then recurse into the side that holds the kth position only: the kth smallest in O(n) on average, without sorting the rest

quicksort is the usual choice in memory: in place, cache friendly, and fast on
average. merge sort when ties must keep their order, or when n log n has to be
guaranteed. heap sort guarantees it in place.

## practice

- [sort an array](https://leetcode.com/problems/sort-an-array/): sort it yourself. if the input has runs of equal keys, three-way partitioning helps
- [sort colors](https://leetcode.com/problems/sort-colors/): the dutch national flag, in one pass
- [kth largest element in an array](https://leetcode.com/problems/kth-largest-element-in-an-array/): quickselect
- [k closest points to origin](https://leetcode.com/problems/k-closest-points-to-origin/): quickselect on distances
- [move zeroes](https://leetcode.com/problems/move-zeroes/): lomuto's inner loop. i marks where the next nonzero goes
- [partition list](https://leetcode.com/problems/partition-list/): the partition on a linked list, keeping the order within each side

## how real libraries do it

- **go.** `slices.Sort`, `slices.SortFunc` and `sort.Sort` are pdqsort: insertion sort at 12 items or fewer, a pivot from the median of three or tukey's ninther, which also hints whether the range is already sorted or reversed, a partition for runs of equal keys, a scramble after an unbalanced split, heap sort once `bits.Len(n)` bad splits have happened, and recursion on the shorter side only[^go]
- **rust.** `sort_unstable` is ipnsort, by lukas bergdoll and orson peters: insertion sort up to 20 items, one pass for a fully sorted or reversed slice, then quicksort with a pseudomedian pivot, a partition that collects keys equal to the previous pivot, and heap sort after 2 log₂ n unbalanced partitions. the partition itself is a branchless lomuto for items of 96 bytes or less, and hoare's scheme above that[^rust]
- **java.** `Arrays.sort` on primitives is dual-pivot quicksort: five samples around the middle, the first and fifth as pivots when all five differ and the third alone when they don't, insertion sort under 44 items, merging of runs for nearly sorted input, and heap sort when the recursion gets deep[^java]
- **c.** glibc's `qsort` isn't a quicksort: it's a merge sort, with a buffer on the stack up to 1 kb or else from malloc, and heap sort if the allocation fails. the comment at the top points to bentley and mcilroy's 1993 paper on engineering a sort function[^glibc]
- **python.** its sort merges runs: see the [merge sort](/algos/merge-sort/) page

[^hoare]: c. a. r. hoare, [algorithm 64: quicksort](https://doi.org/10.1145/366622.366644), communications of the acm 4(7), page 321, july 1961, and [quicksort](https://doi.org/10.1093/comjnl/5.1.10), the computer journal 5(1), pages 10 to 16, 1962.

[^algs4]: [quicksort](https://algs4.cs.princeton.edu/23quicksort/), section 2.3 of sedgewick and wayne's _algorithms_, 4th edition: on average quicksort uses about 2n ln n compares, and a sixth as many exchanges, to sort n distinct keys, and about n²/2 in the worst case, which a random shuffle guards against. it puts the invention in 1960, says most of the gain from sampling pivots comes from a sample of 3, describes 3-way partitioning as dijkstra's dutch national flag problem and calls it entropy-optimal, and says stopping both scans on keys equal to the pivot is crucial to avoiding quadratic time.

[^go]: go 1.27.3. [zsortordered.go](https://github.com/golang/go/blob/go1.27.3/src/slices/zsortordered.go#L57-L129): `pdqsortOrdered` is based on pattern-defeating quicksort, after orson peters' pdqsort, without blockquicksort's optimizations. ranges of 12 or fewer go to insertion sort, `limit` counts the bad pivots allowed before heap sort, an unbalanced partition triggers `breakPatterns`, a likely sorted range gets a partial insertion sort, a pivot no bigger than the item before the range means a partition of equal keys, and the shorter side is sorted recursively while the loop continues with the other. [`choosePivotOrdered`](https://github.com/golang/go/blob/go1.27.3/src/slices/zsortordered.go#L258-L297) takes a fixed pivot under 8 items, the median of three under 50 and tukey's ninther above, and reports whether the samples were already in order. [sort.go](https://github.com/golang/go/blob/go1.27.3/src/slices/sort.go#L14-L32) calls it with `bits.Len(n)` as the limit and says `SortFunc` is not guaranteed to be stable, and [sort/sort.go](https://github.com/golang/go/blob/go1.27.3/src/sort/sort.go#L44-L56) does the same for `sort.Sort`.

[^rust]: rust 1.99.1. [slice/mod.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/mod.rs#L3094-L3125): `sort_unstable` is in place, O(n log n) in the worst case, and based on ipnsort by lukas bergdoll and orson peters, with expected O(n log k) time on k distinct elements. [unstable/mod.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/unstable/mod.rs#L15-L17): the name; [lines 49 to 56](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/unstable/mod.rs#L49-L56): insertion sort at 20 items or fewer; [lines 119 to 137](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/unstable/mod.rs#L119-L137): one pass for a slice that's already one run, and a limit of 2 × floor(log₂ n) unbalanced partitions. [unstable/quicksort.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/unstable/quicksort.rs#L30-L79): heap sort when the limit runs out, a partition into equal and greater when the pivot equals the previous one, and recursion on the left side while the loop continues on the right; [its partition](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/unstable/quicksort.rs#L139-L155) is a branchless lomuto for types of 96 bytes or less, and hoare's scheme otherwise. [shared/pivot.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/shared/pivot.rs#L5-L51): the median of three under 64 items and a recursive pseudomedian above, from glidesort, sampling about n^0.528 items.

[^java]: jdk 27. [Arrays.java](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/Arrays.java#L91-L99): `sort(int[])` is a dual-pivot quicksort by vladimir yaroslavskiy, jon bentley and joshua bloch, with O(n log n) performance on all data sets. [DualPivotQuicksort.java](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/DualPivotQuicksort.java#L35-L47) lists the other sorts it calls: mixed insertion sort, merging of runs, heap sort, counting sort and parallel merge sort. [its constants](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/DualPivotQuicksort.java#L64-L124): insertion sort below 44 items, mixed insertion sort below 65 plus the depth counter on parts that aren't leftmost, and a recursion limit of 64 × 6. [the sort loop](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/DualPivotQuicksort.java#L255-L392): a try at merging runs, heap sort when the depth counter passes the limit, five samples spaced around the middle, the first and fifth as pivots when all five differ and the third alone otherwise, then a loop along the left part.

[^glibc]: glibc 2.42, [stdlib/qsort.c](https://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/qsort.c;hb=glibc-2.42#l393): `__qsort_r` merge sorts with a buffer on the stack when the data fits in 1,024 bytes, otherwise with one from malloc, and falls back to heap sort when that allocation fails. [the merge](https://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/qsort.c;hb=glibc-2.42#l196) takes from the left on ties, [elements over 32 bytes](https://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/qsort.c;hb=glibc-2.42#l183) are sorted through pointers, and [the top of the file](https://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/qsort.c;hb=glibc-2.42#l18) points to bentley and mcilroy's _engineering a sort function_, 1993.

[^musser]: david r. musser, [introspective sorting and selection algorithms](https://doi.org/10.1002/%28SICI%291097-024X%28199708%2927:8%3C983::AID-SPE117%3E3.0.CO;2-%23), software: practice and experience 27(8), pages 983 to 993, 1997.

## related

- https://learning.anthnydas.com/algos/merge-sort.md
- https://learning.anthnydas.com/algos/heap-sort.md
- https://learning.anthnydas.com/algos/insertion-sort.md
- https://learning.anthnydas.com/algos/big-o.md
- https://learning.anthnydas.com/algos/two-pointers.md
