algossorting

heap sort

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

report a mistake
.md

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

heap sort is selection sort with a better way to find the biggest item. a max-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.1

the idea

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.

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.

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.

input
40113293745586
40
11
32
93
74
55
86

7 items as they came, drawn as a tree: slot i's children are slots 2i + 1 and 2i + 2. the back half are leaves, heaps of one already

comparisons
0
swaps
0
in the heap
7 of 7
step
1 of 41
pseudocode
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

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.

build a max-heap from this array. the build sifts down one parent at a time, the last one first. tap the slot it starts at.

40113293745586

tap a slot.

0 / 0 right

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

pseudocode
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

why it’s n log n

01231814extractlevels
can sink
31 levels in all: the ceiling
did sink
25 on a shuffled array, 1.79 an extract
at the ceiling
8 of 14 extracts

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.

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.

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

variants

practice

how real libraries use it

sources

  1. heapsort (opens in a new tab) 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. ↩

  2. lib/sort.c (opens in a new tab) 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 (opens in a new tab) 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 (opens in a new tab) 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. ↩ ↩2

  3. stl_algo.h (opens in a new tab) 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 (opens in a new tab)’s doc says the relative order of equivalent elements isn’t preserved. ↩ ↩2

  4. zsortfunc.go (opens in a new tab) 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 (opens in a new tab) sets the limit to the bit length of n, and slices.Sort (opens in a new tab) does the same with a copy of its own (opens in a new tab). ↩ ↩2

  5. rust 1.99.1. quicksort.rs (opens in a new tab): 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 (opens in a new tab) sets the limit to 2 × floor(log₂ len), and with optimize_for_size (opens in a new tab) sorts with heapsort alone. heapsort.rs (opens in a new tab) is a branchless heapsort meant as an unlikely fallback. the docs (opens in a new tab) say the implementation is based on ipnsort, which combines the fast average case of quicksort with the fast worst case of heapsort. ↩ ↩2

  6. smoothsort, an alternative for sorting in situ (opens in a new tab), 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. ↩

  7. DualPivotQuicksort.java (opens in a new tab) at jdk-27-ga: MAX_RECURSION_DEPTH, 64 × DELTA, is the most partitioning depth before heap sort, and the sort (opens in a new tab) switches to heapSort past it, with a comment that the execution time is becoming quadratic. its heap sort (opens in a new tab) pushes the parents down from the middle back to the start, then moves the max to the end one at a time. ↩

  8. qsort.c (opens in a new tab) 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 (opens in a new tab), 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. ↩

  9. heapq (opens in a new tab) 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. ↩