# heap sort

> build a max-heap in place, then move the biggest item to the back, one at a time.

source: https://learning.anthnydas.com/algos/heap-sort/

## tl;dr

turn the array into a max-heap where it sits, then swap the top to the back n - 1 times, sifting the new top down the heap that's left.

- **time:** O(n log n) (best, average and worst)
- **space:** O(1) (in place, no buffer, no recursion)
- **build:** O(n) (fewer than n swaps)
- **stable:** no (equal items can swap places)
- **comparisons:** ~2n log₂ n (two per level of every sift)
- **reach for it:** a guaranteed n log n with no extra memory, the fallback in introsort-style sorts, when quicksort goes bad, kernels and small devices, where a buffer or deep recursion is a problem, the k biggest items: stop after k extracts

heap sort is selection sort with a better way to find the biggest item. a [max-heap](/ds/heap/) keeps the biggest on top, in the array itself, with no pointers. so build one in place, then swap the top with the last item of the heap, over and over. each swap puts one more item in its final place, at the front of a sorted tail that grows from the back. j. w. j. williams published it in 1964, and the binary heap with it. robert floyd improved it the same year, with the bottom-up build this page uses.[^history]

## the idea

> **interactive figure:** an animation in six steps. seven numbers, 4, 1, 3, 9, 7, 5 and 8, sit in an array, and a tree draws itself over them: slot i's children are slots 2i + 1 and 2i + 2. the build sifts the parents down, last to first: 3 sinks under 8, 1 under 9, and 4 under 9 and then under 7, leaving a max-heap, 9, 7, 8, 1, 4, 5, 3. then the top, 9, swaps with the last item in the heap, 3, and leaves the tree: slot 6 fades, the first of the sorted tail. 3 sifts down past 8 and 5 to slot 5. the extract repeats five more times, each one moving the next biggest to the front of the sorted tail, until the tree is empty and the array reads 1, 3, 4, 5, 7, 8, 9. counts of comparisons and swaps run in the corners: 20 and 16 at the end.

seven numbers in no particular order. read the array as a tree: slot i's children are slots 2i + 1 and 2i + 2. the back half, 9, 7, 5 and 8, are leaves, heaps of one already. nothing else is in heap order yet.

build a max-heap, bottom up. the last parent is slot 2, so 3 sinks under 8. then 1 sinks under 9. then the root: 4 sinks under 9, and again under 7. four swaps, and the biggest, 9, is on top.

extract: swap the top with the last item in the heap. 9 goes to slot 6, its final place, and 3 comes up to the top. the heap is the first 6 slots now, and the sorted tail starts at slot 6.

3 doesn't belong on top, so it sifts down: its bigger child is 8, then 5. two swaps, and the heap is a heap again, with 8 on top.

the same move, five more times: 8, 7, 5, 4 and 3 go to the back of the heap in turn, each in its final place, and the heap shrinks to nothing.

the array is sorted, smallest first: 20 comparisons and 16 swaps, all in place. the heap page's seven numbers, in order.

## watch it run

step through a real run. the tree on top is the heap, and the array under it is where it lives. during the build the parents not reached yet are faded. each extract swaps the top, in white, to the back of the heap, where the sorted tail is dimmed, and the new top sinks with its children in cyan for left and amber for right. the pseudocode follows along.

> **interactive figure:** an interactive stepper: the page's seven numbers, or 7, 10 or 15 random ones, drawn as a tree above the array they live in, sorted by heap sort one step at a time. the build fades the parents it hasn't reached yet. each extract swaps the top to the back of the heap, where the sorted tail is dimmed, and the new top sinks with its two children in cyan and amber and the moving item in white. the matching pseudocode line is highlighted, with counters for comparisons, swaps and how much of the array is still in the heap.

## try it

heap sort hangs on two facts: where the build starts, and where each extract puts the top. make the calls.

> **interactive figure:** a practice exercise on an array drawn as a tree above its slots, with the sorted tail dimmed. some questions ask where the build starts, answered by tapping a slot. others show a sort midway and ask which slot the top lands in on the next extract, where the item that comes up stops after sifting down, or which of a few rows is the whole array after.

## pseudocode

```text
heap_sort(a):
  n = len(a)
  for i from n // 2 - 1 down to 0:  # build a max-heap, bottom up
    sift_down(a, i, n)
  for end from n - 1 down to 1:  # the biggest is at a[0]
    swap a[0], a[end]  # it goes to the back
    sift_down(a, 0, end)  # the heap is a[0:end] now

sift_down(a, i, n):  # a[0:n] is the heap
  while true:
    big = i
    for c in (2 * i + 1, 2 * i + 2):  # left child, then right
      if c < n and a[c] > a[big]: big = c
    if big == i: return
    swap a[i], a[big]
    i = big
```

`//` is integer division, and `a[0:end]` is `a[0]` up to but not including `a[end]`. ties go the same way in every tab: a child moves up only when it's strictly bigger than its parent, and when both children are equal, the left one. that's what the typescript test checks with records that share a key.

## the extract, up close

- **the top is the biggest.** in a max-heap every parent is at least its children, so `a[0]` is the biggest item in the heap. swapping it with `a[end]`, the heap's last item, drops it right in front of the items already sorted: its final place
- **the heap shrinks by one.** it's `a[0:end]` now, and the item that came up from the back doesn't belong on top. it's usually one of the smallest, since it sat in the bottom row, so it sinks most of the way back down. on the example, 3 comes up in four of the six extracts, and the first three times it sinks all the way back to a leaf
- **sift down, in a loop.** at each level, compare the two children to find the bigger, then compare that child with the parent: two comparisons a level. swap when the child wins, and carry on from its old slot. a leaf has no children in the heap, so the loop stops there at the latest
- **nothing else moves.** one swap takes the top out, and the sift moves one item down one path. everything off that path stays put, which is why the whole sort fits in the array it was given

## why it's n log n

> **interactive figure:** a chart with buttons for 15, 63 or 1,023 items. a cyan step line shows how many levels the new top can sink in each extract, first to last, and amber bars under it show how far it did sink on a shuffled array, each bar one extract, or the average of 16 of them for 1,023 items. the ceiling drops one level each time the heap halves, so most extracts can still sink nearly the full height: for 15 items the first 7 extracts can sink 3 levels, the next 4 two, the next 2 one, and the last none, 31 levels in all, and the shuffled array sank 25 of them. for 1,023 items the ceiling is 8,185 levels, the shuffled array sank 7,521, 7.36 an extract, and 425 of the 1,022 extracts reached the ceiling.

- **the build is O(n).** sifting every parent down, last to first, costs fewer than n swaps in all: half the items are leaves and never move, a quarter can sink one level, and so on. the [heap page](/ds/heap/#building-up-close) counts it: at most n minus the 1 bits of n, 1,013 swaps for 1,023 items. the shuffled 1,023 behind the figure took 739
- **each extract is O(log n).** the new top sinks down a heap of `end` items, which has log₂ end levels under its top, rounded down. for 15 items that's 3 levels for the first 7 extracts, 2 for the next 4, 1 for the next 2, and none for the last: 31 levels at most, and the shuffled 15 used 25 of them
- **the heap loses a level slowly.** it has to lose half its items to drop one level, so most extracts can still sink nearly the full height. over n extracts that's about n log₂ n swaps at worst, two comparisons each: a ceiling of 8,185 levels for 1,023 items, where the shuffled run used 7,521, 7.36 an extract, and 425 of the 1,022 extracts went all the way down
- **the mirror of pushing.** the heap page's build figure counts pushing 15 items one at a time at up to 34 swaps, each item climbing from the bottom row. the extracts walk the same levels downward: 31 for 15 items, 34 minus the root's own 3. the build is the cheap half, the extracts are where the n log n goes, and they go the same way whatever the input

## complexity

heap sort doesn't look at the order it's given. the build sifts every parent and every extract sifts the top, however the input came in, so the best case is the worst case: O(n log n), in place. the chart counts comparisons through each page's reference code, on the same arrays, and flips the input between shuffled, already sorted and reversed.

> **interactive figure:** a line chart of comparisons against how many items there are, from 16 to 4,096 on a doubling scale, for insertion sort, merge sort, quicksort and heap sort on the same arrays, with heap sort's line in cyan and a menu that switches the input between shuffled, already sorted and reversed. on 1,024 shuffled numbers: insertion sort 273,132, merge sort 8,962, quicksort 11,185, heap sort 17,273. already sorted: 1,023, 5,120, 8,204 and 18,060. reversed: 523,776, 5,120, 8,601 and 16,407. heap sort's line barely moves with the input; insertion sort's swings from the bottom of the chart to off the top.

on 1,024 shuffled numbers heap sort makes 17,273 comparisons. hand it the same numbers already in order and it makes 18,060, where insertion sort makes 1,023. reverse them and insertion sort climbs to 523,776 while heap sort drops to 16,407: its three counts never differ by more than a fifth, by less than a tenth from 2,048 items on, and all of them sit between n log₂ n and twice it. reversed input is a max-heap already, so the build swaps nothing, and sorted input is the build's worst case, 1,013 swaps for 1,023 items: either way the extracts cost the same. a million shuffled numbers take 36.8 million comparisons, 1.85 times n log₂ n.

the price is the constant. on the same shuffled 1,024 numbers merge sort makes 8,962 comparisons and quicksort 11,185, since a merge compares one pair per item it moves and a partition compares each item with the pivot once, where a sift compares two children per level. and a sift jumps from slot i to slot 2i + 1, far across the array in a big heap, where merge sort and quicksort walk it in order. so quicksort is usually faster in practice, and heap sort is the one that's safe: the libraries below keep it as the backstop.

## 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 the page's example, 2000 seeded arrays against the language's own sort, and a million numbers, 100,000 in python, with the same tie rules in every tab. the typescript one takes a compare function and shows, with pairs that share a key, that the sort isn't stable. the others sort ints, in place.

`go/algos/heapsort/heapsort.go`

```go
// Package heapsort is a reference heap sort, in place. build a max-heap bottom up, then swap the biggest
// item to the back and sift the new top down the shrinking heap, n - 1 times. O(n log n) time in every
// case, O(1) extra space, not stable.
package heapsort

// Sort sorts a in ascending order.
func Sort(a []int) {
	n := len(a)
	// build: the back half are leaves, heaps of one already. sift down every parent, the last one first
	for i := n/2 - 1; i >= 0; i-- {
		siftDown(a, i, n)
	}
	// extract: the biggest item is at a[0]. swap it behind the heap, which is one shorter now, and fix
	// the top
	for end := n - 1; end > 0; end-- {
		a[0], a[end] = a[end], a[0]
		siftDown(a, 0, end)
	}
}

// siftDown swaps a[i] down with its bigger child until neither child is bigger. a[:n] is the heap.
func siftDown(a []int, i, n int) {
	for {
		left := 2*i + 1
		right := left + 1
		big := i
		if left < n && a[left] > a[big] {
			big = left
		}
		// strictly bigger, so when both children are equal the left one moves up
		if right < n && a[right] > a[big] {
			big = right
		}
		if big == i {
			return
		}
		a[i], a[big] = a[big], a[i]
		i = big
	}
}
```

`rust/algos/src/heap_sort.rs`

```rust
//! heap sort, in place. build a max-heap bottom up, then swap the biggest item to the back and sift the new top down the shrinking heap, n - 1 times. O(n log n) time in every case, O(1) extra space, not stable.

/// Sorts `a` in ascending order, in place.
pub fn heap_sort(a: &mut [i32]) {
    let n = a.len();
    // build: the back half are leaves, heaps of one already. sift down every parent, the last one
    // first
    for i in (0..n / 2).rev() {
        sift_down(a, i, n);
    }
    // extract: the biggest item is at a[0]. swap it behind the heap, which is one shorter now, and
    // fix the top
    for end in (1..n).rev() {
        a.swap(0, end);
        sift_down(a, 0, end);
    }
}

/// Swaps `a[i]` down with its bigger child until neither child is bigger. `a[..n]` is the heap.
fn sift_down(a: &mut [i32], mut i: usize, n: usize) {
    loop {
        let left = 2 * i + 1;
        let right = left + 1;
        let mut big = i;
        if left < n && a[left] > a[big] {
            big = left;
        }
        // strictly bigger, so when both children are equal the left one moves up
        if right < n && a[right] > a[big] {
            big = right;
        }
        if big == i {
            return;
        }
        a.swap(i, big);
        i = big;
    }
}

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

    /// xorshift32 seeded with `seed`, like the other tests here: each call gives the next number.
    fn xorshift32(seed: u32) -> impl FnMut() -> usize {
        let mut state = seed;
        move || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        }
    }

    // the page's example: the heap page's seven numbers, shuffled
    const PAGE: [i32; 7] = [4, 1, 3, 9, 7, 5, 8];

    #[test]
    fn sorts_each_case() {
        let cases: [(&str, &[i32], &[i32]); 8] = [
            ("the empty array", &[], &[]),
            ("one item", &[5], &[5]),
            ("two items, out of order", &[2, 1], &[1, 2]),
            (
                "already sorted",
                &[1, 2, 3, 4, 5, 6, 7, 8],
                &[1, 2, 3, 4, 5, 6, 7, 8],
            ),
            (
                "reversed",
                &[8, 7, 6, 5, 4, 3, 2, 1],
                &[1, 2, 3, 4, 5, 6, 7, 8],
            ),
            ("duplicates", &[3, 1, 3, 1, 2, 2], &[1, 1, 2, 2, 3, 3]),
            ("all the same", &[7, 7, 7, 7], &[7, 7, 7, 7]),
            ("the page's example", &PAGE, &[1, 3, 4, 5, 7, 8, 9]),
        ];
        for (name, input, want) in cases {
            let mut a = input.to_vec();
            heap_sort(&mut a);
            assert_eq!(a, want, "{name}");
        }
    }

    #[test]
    fn sorts_in_place_and_hands_nothing_back() {
        // the type says the second half: it takes the slice and returns nothing
        let _: fn(&mut [i32]) = heap_sort;
        let mut a = [3, 1, 2];
        heap_sort(&mut a);
        assert_eq!(a, [1, 2, 3]);
    }

    #[test]
    fn agrees_with_the_built_in_sort_on_2000_seeded_arrays() {
        let mut next = xorshift32(42);
        for _ in 0..2000 {
            // small values, so most arrays have duplicates
            let input: Vec<i32> = (0..next() % 40).map(|_| (next() % 20) as i32).collect();
            let mut got = input.clone();
            heap_sort(&mut got);
            let mut want = input.clone();
            want.sort();
            assert_eq!(got, want);
        }
    }

    #[test]
    fn a_million_items_in_place() {
        let mut next = xorshift32(7);
        let mut a: Vec<i32> = (0..1_000_000)
            .map(|_| (next() % 1_000_000) as i32)
            .collect();
        let mut want = a.clone();
        want.sort();
        heap_sort(&mut a);
        assert_eq!(a, want);
    }
}
```

`site/src/visuals/heap-sort/heap-sort.ts`

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

/**
 * Heap sort, in place. Build a max-heap bottom up, then swap the biggest item to the back and sift the new top
 * down the shrinking heap, n - 1 times. O(n log n) time in every case, O(1) extra space, not stable.
 */
export function heapSort<T>(a: T[], compare: (a: T, b: T) => number = ascending): void {
  const n = a.length;
  // build: the back half are leaves, heaps of one already. sift down every parent, the last one first
  for (let i = Math.floor(n / 2) - 1; i >= 0; i--) siftDown(a, i, n, compare);
  // extract: the biggest item is at a[0]. swap it behind the heap, which is one shorter now, and fix the top
  for (let end = n - 1; end > 0; end--) {
    [a[0], a[end]] = [a[end], a[0]];
    siftDown(a, 0, end, compare);
  }
}

/** Swap a[i] down with its bigger child until neither child is bigger. a[0:n] is the heap. */
function siftDown<T>(a: T[], i: number, n: number, compare: (a: T, b: T) => number): void {
  for (;;) {
    const left = 2 * i + 1;
    const right = left + 1;
    let big = i;
    if (left < n && compare(a[left], a[big]) > 0) big = left;
    // strictly bigger, so when both children are equal the left one moves up
    if (right < n && compare(a[right], a[big]) > 0) big = right;
    if (big === i) return;
    [a[i], a[big]] = [a[big], a[i]];
    i = big;
  }
}
```

`c/algos/heap_sort.c`

```c
/* heap sort, in place. build a max-heap bottom up, then swap the biggest item to the back and sift the new top down the shrinking heap, n - 1 times. O(n log n) time in every case, O(1) extra space, not stable. */
#include "heap_sort.h"

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

/* swaps a[i] down with its bigger child until neither child is bigger. a[0..n) is the heap */
static void sift_down(int *a, size_t i, size_t n) {
    for (;;) {
        size_t left = 2 * i + 1, right = left + 1, big = i;
        if (left < n && a[left] > a[big]) big = left;
        /* strictly bigger, so when both children are equal the left one moves up */
        if (right < n && a[right] > a[big]) big = right;
        if (big == i) return;
        swap(a, i, big);
        i = big;
    }
}

void heap_sort(int *a, size_t n) {
    if (n == 0) return; /* end = n - 1 below would wrap around to SIZE_MAX */
    /* build: the back half are leaves, heaps of one already. sift down every parent, the last one
       first: a[n / 2 - 1] down to a[0]. i runs one ahead, n / 2 down to 1, since a size_t can't go
       below 0 to end the loop */
    for (size_t i = n / 2; i > 0; i--) sift_down(a, i - 1, n);
    /* extract: the biggest item is at a[0]. swap it behind the heap, which is one shorter now, and
       fix the top */
    for (size_t end = n - 1; end > 0; end--) {
        swap(a, 0, end);
        sift_down(a, 0, end);
    }
}
```

`swift/algos/HeapSort.swift`

```swift
/// heap sort, in place. build a max-heap bottom up, then swap the biggest item to the back and sift the new top down the shrinking heap, n - 1 times. O(n log n) time in every case, O(1) extra space, not stable.
public func heapSort(_ a: inout [Int]) {
    let n = a.count
    // build: the back half are leaves, heaps of one already. sift down every parent, the last one first
    for i in stride(from: n / 2 - 1, through: 0, by: -1) { siftDown(&a, i, n) }
    // extract: the biggest item is at a[0]. swap it behind the heap, which is one shorter now, and fix the top
    for end in stride(from: n - 1, to: 0, by: -1) {
        a.swapAt(0, end)
        siftDown(&a, 0, end)
    }
}

// swaps a[i] down with its bigger child until neither child is bigger. a[0..<n] is the heap
private func siftDown(_ a: inout [Int], _ i: Int, _ n: Int) {
    var i = i
    while true {
        let left = 2 * i + 1
        let right = left + 1
        var big = i
        if left < n && a[left] > a[big] { big = left }
        // strictly bigger, so when both children are equal the left one moves up
        if right < n && a[right] > a[big] { big = right }
        if big == i { return }
        a.swapAt(i, big)
        i = big
    }
}
```

`python/algos/heap_sort.py`

```python
"""heap sort, in place. build a max-heap bottom up, then swap the biggest item to the back and sift the new top down the shrinking heap, n - 1 times. O(n log n) time in every case, O(1) extra space, not stable."""

from __future__ import annotations


def heap_sort(a: list[int]) -> None:
    """Sort a in place, smallest first."""
    n = len(a)
    # build: the back half are leaves, heaps of one already. sift down every parent, the last one first
    for i in range(n // 2 - 1, -1, -1):
        _sift_down(a, i, n)
    # extract: the biggest item is at a[0]. swap it behind the heap, which is one shorter now, and fix
    # the top
    for end in range(n - 1, 0, -1):
        a[0], a[end] = a[end], a[0]
        _sift_down(a, 0, end)


def _sift_down(a: list[int], i: int, n: int) -> None:
    """Swap a[i] down with its bigger child until neither child is bigger. a[0:n] is the heap."""
    while True:
        left = 2 * i + 1
        right = left + 1
        big = i
        if left < n and a[left] > a[big]:
            big = left
        # strictly bigger, so when both children are equal the left one moves up
        if right < n and a[right] > a[big]:
            big = right
        if big == i:
            return
        a[i], a[big] = a[big], a[i]
        i = big
```

## pitfalls

- **a min-heap.** sorting smallest first needs a max-heap, so the biggest can go to the back. with a min-heap the array comes out biggest first, or the items have to go into a second array
- **sifting through the tail.** after an extract the heap is `a[0:end]`. sift with `n` instead of `end` and the item just placed at the back gets pulled back into the heap
- **building top down.** the parents have to go last to first: a parent sinks through heaps, so the heaps below it come first. sifting from slot 0 upward doesn't build a heap. and starting at `n - 1` instead of `n // 2 - 1` is only wasted work: leaves don't move
- **the smaller child.** swap with the bigger child. swap with the smaller one and the bigger child ends up under a smaller parent, and the heap is broken
- **expecting stability.** records with equal keys can come out reordered. the typescript test shows it with four pairs: 2a, 1b, 2c, 1d come out b, d, c, a
- **counting on it being fast.** it's n log n in every case, but each sift hops across the array, so on real hardware quicksort usually wins. heap sort is the guarantee, not the fast path

## variants

- **bottom-up heap sort.** sift down without comparing the moved item on the way: follow the bigger child to a leaf, one comparison per level, then climb back up to where the item belongs. the linux kernel's `sort()` does this, and its comment counts a bit more than half as many comparisons on average[^linux]. the heap page's bottom-up pop is the same idea
- **the k biggest.** stop after k extracts: O(n) for the build plus O(k log n) for the extracts. with a heap of k items instead, a stream of any length fits
- **introsort.** quicksort with a depth limit, and heap sort when the limit runs out: quicksort's speed with heap sort's worst case. libstdc++'s `std::sort` is one,[^libstdcxx] go's unstable sort does the same with pattern-defeating quicksort,[^go] and rust's with ipnsort[^rust]
- **smoothsort.** dijkstra's variant, built on a run of leonardo heaps instead of one binary heap: n log n in the worst case, and O(n) on input that's sorted already, which heap sort can't do[^smoothsort]

heap sort is the sort to reach for when the worst case has to be n log n and
there's no room for a buffer. for everything else, quicksort is faster in
memory, and merge sort is stable.

## practice

- [sort an array](https://leetcode.com/problems/sort-an-array/): the whole thing, in place, with no library sort
- [kth largest element in an array](https://leetcode.com/problems/kth-largest-element-in-an-array/): build a max-heap and extract k times
- [k closest points to origin](https://leetcode.com/problems/k-closest-points-to-origin/): the k smallest by a key, out of a heap
- [sort characters by frequency](https://leetcode.com/problems/sort-characters-by-frequency/): count, then heap sort by count
- [the k weakest rows in a matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/): a key of two parts, then the k smallest
- [kth smallest element in a sorted matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/): a heap over the rows' heads, popped k times

## how real libraries use it

- **go.** `sort.Sort` and `slices.Sort` run pattern-defeating quicksort with a budget of bad pivots, the bit length of n. when the budget is spent, heap sort finishes the slice[^go]
- **rust.** `sort_unstable` is ipnsort, which its docs describe as quicksort's average case with heapsort's worst case. its quicksort allows 2 log₂ n imbalanced partitions, then calls heapsort. built for size, it's heapsort from the start[^rust]
- **c++.** libstdc++'s `std::sort` is introsort: a depth limit of 2 log₂ n, a heap sort of whatever's left when it runs out, and insertion sort to finish[^libstdcxx]
- **java.** `Arrays.sort` on primitives is a dual-pivot quicksort that switches to heap sort past a fixed recursion depth, where its comment says the running time is turning quadratic[^java]
- **glibc.** `qsort` is a merge sort with a buffer. when the buffer can't be allocated it falls back to a heapsort, which needs no memory at all[^glibc]
- **linux.** the kernel's `sort()` is a heapsort and nothing else. its comment says quicksort is slightly faster on average, but its exploitable n² worst case and extra memory make it less suitable for the kernel. the heap sort there is non-recursive and bottom-up, about n log₂ n + 0.37n comparisons on average[^linux]
- **python.** the `heapq` docs show heapsort as a short example, push everything then pop it all, and note that unlike `sorted` it isn't stable[^heapqdocs]

[^history]: [heapsort](https://en.wikipedia.org/wiki/Heapsort) on wikipedia, which cites williams, "algorithm 232 – heapsort", _communications of the acm_ 7(6), 1964, and floyd, "algorithm 245 – treesort 3", _communications of the acm_ 7(12), 1964: williams invented heapsort, and his paper introduced the binary heap; floyd published an improved version the same year, and the O(n) bottom-up heap construction, used by every practical heapsort since, is his.

[^go]: [zsortfunc.go](https://github.com/golang/go/blob/go1.27.3/src/sort/zsortfunc.go#L55-L81) at go1.27.3: `pdqsort_func`'s `limit` is the number of bad, very unbalanced pivots allowed before falling back to heapsort, and when it reaches 0 the slice goes to `heapSort_func`, which builds a heap with the greatest element on top and pops the largest into the end. [`Sort`](https://github.com/golang/go/blob/go1.27.3/src/sort/sort.go#L44-L57) sets the limit to the bit length of n, and [`slices.Sort`](https://github.com/golang/go/blob/go1.27.3/src/slices/sort.go#L14-L33) does the same with [a copy of its own](https://github.com/golang/go/blob/go1.27.3/src/slices/zsortanyfunc.go#L38-L81).

[^rust]: rust 1.99.1. [quicksort.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/unstable/quicksort.rs#L14-L40): `limit` is the number of imbalanced partitions allowed before switching to heapsort, and at zero it falls back to heapsort to guarantee O(n log n) in the worst case. [mod.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/unstable/mod.rs#L134-L137) sets the limit to 2 × floor(log₂ len), and [with `optimize_for_size`](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/unstable/mod.rs#L38-L41) sorts with heapsort alone. [heapsort.rs](https://github.com/rust-lang/rust/blob/1.99.1/library/core/src/slice/sort/unstable/heapsort.rs#L1-L31) is a branchless heapsort meant as an unlikely fallback. the [docs](https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable) say the implementation is based on ipnsort, which combines the fast average case of quicksort with the fast worst case of heapsort.

[^libstdcxx]: [stl_algo.h](https://github.com/gcc-mirror/gcc/blob/releases/gcc-15.2.0/libstdc++-v3/include/bits/stl_algo.h#L1873-L1911) in libstdc++ at gcc 15.2.0: `__introsort_loop` partitions while a depth limit lasts, and at 0 hands the range to `__partial_sort`, which is `__heap_select` followed by `__sort_heap`. `__sort` starts the loop with a limit of 2 × log₂ n and finishes with `__final_insertion_sort`. [`std::sort`](https://github.com/gcc-mirror/gcc/blob/releases/gcc-15.2.0/libstdc++-v3/include/bits/stl_algo.h#L4815-L4841)'s doc says the relative order of equivalent elements isn't preserved.

[^java]: [DualPivotQuicksort.java](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/DualPivotQuicksort.java#L116-L124) at jdk-27-ga: `MAX_RECURSION_DEPTH`, 64 × `DELTA`, is the most partitioning depth before heap sort, and [the sort](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/DualPivotQuicksort.java#L281-L288) switches to `heapSort` past it, with a comment that the execution time is becoming quadratic. [its heap sort](https://github.com/openjdk/jdk/blob/jdk-27-ga/src/java.base/share/classes/java/util/DualPivotQuicksort.java#L700-L716) pushes the parents down from the middle back to the start, then moves the max to the end one at a time.

[^glibc]: [qsort.c](https://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/qsort.c;hb=glibc-2.42#l393) in glibc 2.42: `__qsort_r` runs a merge sort in a buffer on the stack when the input is small, or in one from `malloc`, and when that fails it falls back to [`heapsort_r`](https://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/qsort.c;hb=glibc-2.42#l145), a non-recursive heapsort with O(n log n) worst-case time and O(1) space, which builds the heap with the largest value at the front and extracts the largest into the end.

[^linux]: [lib/sort.c](https://github.com/torvalds/linux/blob/v7.2/lib/sort.c#L2-L11) in linux v7.2: a fast, small, non-recursive O(n log n) sort, with n log₂ n + 0.37n + o(n) comparisons on average and 1.5 n log₂ n + O(n) in a contrived worst case, where quicksort gets n log₂ n − 1.26n on random input at the cost of stack use and much more code to avoid its O(n²) worst case. [`sort_r`](https://github.com/torvalds/linux/blob/v7.2/lib/sort.c#L277-L302) does a heapsort, O(n log n) on average and in the worst case, and its comment says quicksort is slightly faster on average but has an exploitable O(n²) worst case and needs extra memory, which make it less suitable for kernel use. [the sift](https://github.com/torvalds/linux/blob/v7.2/lib/sort.c#L241-L252) is the bottom-up variant: one comparison per level down to a leaf, then a walk back up, a bit more than half as many comparisons on average.

[^smoothsort]: [smoothsort, an alternative for sorting in situ](https://www.cs.utexas.edu/~EWD/transcriptions/EWD07xx/EWD796a.html), ewd796a in the e. w. dijkstra archive: inspired by heapsort, it sorts in place in O(n log n) in the worst case and O(n) in the best.

[^heapqdocs]: [heapq](https://docs.python.org/3/library/heapq.html) in the python docs: the basic examples implement a heapsort by pushing every value onto a heap and popping the smallest off one at a time, which is like `sorted` but not stable.

## related

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