algossorting

quicksort

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

report a mistake
.md

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
on this page
  1. the idea
  2. watch it run
  3. try it
  4. pseudocode
  5. the partition, up close
  6. complexity
  7. implementations
  8. pitfalls
  9. variants
  10. practice
  11. how real libraries do it
  12. sources

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,1 and the unstable sorts in go, rust and java are still built on it.

the idea

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

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.

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.

input

8 items to sort

comparisons
0
swaps
0
depth
0
deepest
0
stack
0
step
1 of 48
pseudocode
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

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.

the pivot is the middle item, 29. which index does it land at?

tap an index.

0 / 0 right

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

pseudocode
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

  • lo up to i: below the pivot. 12 and 23, in the order j found them
  • i up to j: not below it. 51 and 34
  • j: 17, the item being looked at. after it, 8 and 45 haven't been seen
  • hi - 1: the pivot, 29, parked out of the way until the scan is over

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.

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

input
020k40k60k80k100k162564096insertion sort
insertion sort
4,255,320 comparisons
merge sort
43,932 comparisons
quicksort
59,922 comparisons
heap sort
85,650 comparisons

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.

levels of partitioning, with the pivot as
010203040162564096all equal
random input
27 deep
sorted input
12 deep
all equal
4,095 deep
stack, random input
7 deep
stack, sorted input
11 deep
log₂ n
12 deep

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
// 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
//! 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
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
/* 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
/// 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
"""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

variants

practice

how real libraries do it

sources

  1. c. a. r. hoare, algorithm 64: quicksort (opens in a new tab), communications of the acm 4(7), page 321, july 1961, and quicksort (opens in a new tab), the computer journal 5(1), pages 10 to 16, 1962. ↩

  2. quicksort (opens in a new tab), 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. ↩ ↩2 ↩3 ↩4

  3. rust 1.99.1. slice/mod.rs (opens in a new tab): 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 (opens in a new tab): the name; lines 49 to 56 (opens in a new tab): insertion sort at 20 items or fewer; lines 119 to 137 (opens in a new tab): one pass for a slice that’s already one run, and a limit of 2 × floor(log₂ n) unbalanced partitions. unstable/quicksort.rs (opens in a new tab): 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 (opens in a new tab) is a branchless lomuto for types of 96 bytes or less, and hoare’s scheme otherwise. shared/pivot.rs (opens in a new tab): the median of three under 64 items and a recursive pseudomedian above, from glidesort, sampling about n^0.528 items. ↩ ↩2 ↩3 ↩4 ↩5

  4. go 1.27.3. zsortordered.go (opens in a new tab): 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 (opens in a new tab) 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 (opens in a new tab) calls it with bits.Len(n) as the limit and says SortFunc is not guaranteed to be stable, and sort/sort.go (opens in a new tab) does the same for sort.Sort. ↩ ↩2 ↩3 ↩4 ↩5

  5. david r. musser, introspective sorting and selection algorithms (opens in a new tab), software: practice and experience 27(8), pages 983 to 993, 1997. ↩

  6. jdk 27. Arrays.java (opens in a new tab): 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 (opens in a new tab) lists the other sorts it calls: mixed insertion sort, merging of runs, heap sort, counting sort and parallel merge sort. its constants (opens in a new tab): 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 (opens in a new tab): 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. ↩ ↩2 ↩3 ↩4

  7. glibc 2.42, stdlib/qsort.c (opens in a new tab): __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 (opens in a new tab) takes from the left on ties, elements over 32 bytes (opens in a new tab) are sorted through pointers, and the top of the file (opens in a new tab) points to bentley and mcilroy’s engineering a sort function, 1993. ↩