data structurestrees

heap

a tree packed into an array, smallest item on top. it's how a priority queue works.

report a mistake
.md

a tree where every parent is at most its children, stored row by row in an array. the smallest item is always at index 0.

peek
O(1) the smallest is at index 0
push
O(log n) at most one swap per level
pop
O(log n) the last item goes on top and sinks
build from n items
O(n) most items sit near the bottom
find an item
O(n) a heap isn't sorted
reach for it
  • priority queues and schedulers
  • the frontier in dijkstra and a*
  • the k smallest or largest of a stream
  • merging k sorted lists
  • heap sort
on this page
  1. the idea
  2. the easy part
  3. the operations
  4. try it
  5. pseudocode
  6. building, up close
  7. complexity
  8. implementations
  9. pitfalls
  10. variants
  11. practice
  12. how real libraries do it
  13. sources

a heap keeps its smallest item on top, and nothing else in order. every parent is at most its two children, so the smallest is always at the root, but siblings can come in any order. that loose rule is enough for a priority queue: push anything, pop the smallest. and the tree packs into a plain array, with no pointers at all.

the idea

every parent is at most its children, so the smallest item, 1, sits on top. siblings can come in any order: 3 on the left and 5 on the right is fine.

an animation in six steps. a heap of seven numbers, 1, 3, 5, 4, 8, 9 and 7, is drawn as a tree with 1 on top. the same items appear below as an array, row by row, with slot 1 and its children at slots 3 and 4 marked. 2 is pushed into the next free slot, under 4, and swaps up past 4 and 3 to stop under 1. then the top, 1, is popped: the last item, 4, moves into the top slot and swaps down past 2 and 3.

the easy part

the shape never changes. every row is full except the last, which fills from the left. that’s what makes the array work: slot i always has the same two children, so there are no gaps and nothing to point at.

peek is free: the smallest is at index 0. and there aren’t many levels. 15 items make 4 of them, and a million make 20. push and pop move one item one level per swap, so neither costs more than O(log n).

the operations

10315243849576
10
31
52
43
84
95
76
out

push a small number and watch it climb. pop takes the top out. build makes a heap from 10 random numbers in one pass.

swaps
0
average per push
-
pseudocode
push(h, x):  h.items.append(x)  # the next free slot  sift_up(h, len(h.items) - 1) sift_up(h, i):  while i > 0:    parent = (i - 1) // 2    if h.items[parent] <= h.items[i]: return    swap h.items[parent], h.items[i]    i = parent pop(h):  # h is not empty  top = h.items[0]  last = h.items.pop()  # take the last item off the end  if h.items:    h.items[0] = last    sift_down(h, 0)  return top sift_down(h, i):  n = len(h.items)  while true:    small = i    for c in (2 * i + 1, 2 * i + 2):  # left child, then right      if c < n and h.items[c] < h.items[small]: small = c    if small == i: return    swap h.items[i], h.items[small]    i = small build(xs):  # O(n)  h.items = copy of xs  for i from len(xs) // 2 - 1 down to 0:    sift_down(h, i)

an interactive min-heap that starts as 1, 3, 5, 4, 8, 9 and 7, drawn as a tree above the array it lives in, with each slot's index under its node. buttons push a number you type, pop the top, or build a heap from 10 random numbers. every swap moves in both views at once: the moving item is white, and when an item sinks, its two children are cyan for left and amber for right. during a build, the parents not reached yet are faded. the matching pseudocode line is highlighted, with counters for the swaps and the average swaps per push.

push a small number, like 2, and watch it climb in both views at once. pop moves the last item to the top, and it sinks back down. build fills the heap with 10 random numbers in one pass: the faded slots are the parents it hasn’t reached yet.

try it

push 2. tap the slot where it ends up.

103152438495762

tap a slot.

0 / 0 right

a practice exercise on a heap drawn as a tree above its array. some questions push a number and ask which slot it ends up in, answered by tapping a slot, or how many swaps it takes. others ask what's on top after a pop, or which index holds the parent of a given index.

pseudocode

pseudocode
push(h, x):
  h.items.append(x)  # the next free slot
  sift_up(h, len(h.items) - 1)

sift_up(h, i):
  while i > 0:
    parent = (i - 1) // 2
    if h.items[parent] <= h.items[i]: return
    swap h.items[parent], h.items[i]
    i = parent

pop(h):  # h is not empty
  top = h.items[0]
  last = h.items.pop()  # take the last item off the end
  if h.items:
    h.items[0] = last
    sift_down(h, 0)
  return top

sift_down(h, i):
  n = len(h.items)
  while true:
    small = i
    for c in (2 * i + 1, 2 * i + 2):  # left child, then right
      if c < n and h.items[c] < h.items[small]: small = c
    if small == i: return
    swap h.items[i], h.items[small]
    i = small

build(xs):  # O(n)
  h.items = copy of xs
  for i from len(xs) // 2 - 1 down to 0:
    sift_down(h, i)

// is integer division. the ties go the same way in every tab: a push stops at an equal parent, and when both children are equal and smaller, the left one moves up.

building, up close

you could build a heap from n items by pushing them one at a time. that’s O(n log n) in the worst case. building in place is O(n), by working from the bottom up.

build, sifting down
1013 swaps at most
one push at a time
up to 8194

a bar chart of the worst-case swaps at each level of a heap of 15, 63 or 1023 items, with the root's level at the top. cyan bars are a build, which sifts each parent down; amber bars push the items one at a time, each climbing to the top. the cyan bars stay small, since the many items near the bottom sink a level or two at most. the amber bars grow toward the bottom, where most items are and the climb is longest. for 1023 items, a build takes at most 1013 swaps, and one push at a time up to 8194.

complexity

operationworstaverage
peekO(1)O(1)
pushO(log n)O(1)
popO(log n)O(log n)
build from nO(n)O(n)
find an itemO(n)O(n)

the average is over items that arrive in random order. the average push is O(1): a random new item is usually bigger than its parent already, and stops after a swap or two. rust’s documentation says the same of its binary heap.2 on 1023 random numbers, the pushes averaged about 1.2 swaps each. a pop doesn’t get that break. the item that moves to the top came from the bottom row, so it’s usually one of the biggest, and it sinks most of the way back.

the array behind the heap grows like a dynamic array, so the push that grows it costs O(n) once, and pushes stay O(log n) amortized.

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 pushes, pops and peeks checked against the language’s own heap: python’s heapq, go’s container/heap and rust’s BinaryHeap. swift, c and typescript have none, so they check against a sorted array. an empty heap is where they differ: go returns false, rust None, typescript undefined, c returns false, swift nil, and python raises IndexError.

go/algos/minheap/minheap.go
// Package minheap is a reference binary min-heap: O(1) peek, O(log n) push and pop, O(n) to build
// from n items. packed into an array, with item i's children at 2i + 1 and 2i + 2.
package minheap

import "slices"

// Heap is a min-heap of ints: every parent is at most its children, so the smallest item is at index 0.
// The zero value is an empty heap, ready to use.
type Heap struct {
	items []int
}

// From builds a heap from a copy of values in O(n): it sifts down every parent, the last one first.
func From(values []int) *Heap {
	h := &Heap{items: slices.Clone(values)}
	// items from len/2 on are leaves, so the last parent is at len/2 - 1
	for i := len(h.items)/2 - 1; i >= 0; i-- {
		h.siftDown(i)
	}
	return h
}

// Len returns how many items are in the heap.
func (h *Heap) Len() int {
	return len(h.items)
}

// Peek returns the smallest item without removing it, or false if the heap is empty.
func (h *Heap) Peek() (int, bool) {
	if len(h.items) == 0 {
		return 0, false
	}
	return h.items[0], true
}

// Push adds x at the end, then swaps it up while it's smaller than its parent.
func (h *Heap) Push(x int) {
	h.items = append(h.items, x)
	h.siftUp(len(h.items) - 1)
}

// Pop removes and returns the smallest item, or false if the heap is empty.
// The last item moves to the top and sifts down.
func (h *Heap) Pop() (int, bool) {
	if len(h.items) == 0 {
		return 0, false
	}
	top := h.items[0]
	last := len(h.items) - 1
	h.items[0] = h.items[last]
	h.items = h.items[:last]
	h.siftDown(0) // popping the only item leaves nothing to sift, so that needs no special case
	return top, true
}

// Items returns a copy of the items in array order: slot i is node i of the tree.
func (h *Heap) Items() []int {
	return slices.Clone(h.items)
}

// siftUp swaps item i up while it's smaller than its parent.
func (h *Heap) siftUp(i int) {
	for i > 0 {
		parent := (i - 1) / 2
		if h.items[parent] <= h.items[i] {
			return // an equal parent stops the climb: only a strictly smaller item swaps up
		}
		h.items[parent], h.items[i] = h.items[i], h.items[parent]
		i = parent
	}
}

// siftDown swaps item i down with its smaller child until neither child is smaller.
func (h *Heap) siftDown(i int) {
	n := len(h.items)
	for {
		left, right := 2*i+1, 2*i+2
		small := i
		// strictly smaller only, and left first: of two equal children, the left one moves up
		if left < n && h.items[left] < h.items[small] {
			small = left
		}
		if right < n && h.items[right] < h.items[small] {
			small = right
		}
		if small == i {
			return
		}
		h.items[i], h.items[small] = h.items[small], h.items[i]
		i = small
	}
}
rust/algos/src/min_heap.rs
//! binary min-heap: O(1) peek, O(log n) push and pop, O(n) to build from n items. packed into an array, with item i's children at 2i + 1 and 2i + 2.

/// Integers in a `Vec`, kept so that no item is smaller than its parent: the smallest sits at
/// slot 0. Item `i`'s parent is at `(i - 1) / 2`.
pub struct MinHeap {
    items: Vec<i64>,
}

impl MinHeap {
    /// Makes an empty heap.
    pub fn new() -> Self {
        Self { items: Vec::new() }
    }

    /// The number of items.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Whether there are no items.
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// The smallest item, left in place, or `None` if the heap is empty.
    pub fn peek(&self) -> Option<i64> {
        self.items.first().copied()
    }

    /// Adds `x` at the end, then swaps it up while it's smaller than its parent.
    pub fn push(&mut self, x: i64) {
        self.items.push(x);
        self.sift_up(self.items.len() - 1);
    }

    /// Takes out the smallest item: the last item moves to the top and sifts down. `None` if the
    /// heap is empty.
    pub fn pop(&mut self) -> Option<i64> {
        if self.items.is_empty() {
            return None;
        }
        let top = self.items.swap_remove(0); // the last item fills slot 0
        self.sift_down(0);
        Some(top)
    }

    /// The items in array order: slot `i` is node `i` of the tree.
    pub fn items(&self) -> &[i64] {
        &self.items
    }

    /// Swaps item `i` up while it's smaller than its parent. An equal parent stops the climb.
    fn sift_up(&mut self, mut i: usize) {
        let items = &mut self.items;
        while i > 0 {
            let parent = (i - 1) / 2;
            if items[parent] <= items[i] {
                return;
            }
            items.swap(parent, i);
            i = parent;
        }
    }

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

impl Default for MinHeap {
    fn default() -> Self {
        Self::new()
    }
}

/// Builds a heap from `items` in place: sifts down every parent, the last one first. Most parents
/// sit near the bottom with only a level or two to sink, so the whole build is O(n).
impl From<Vec<i64>> for MinHeap {
    fn from(items: Vec<i64>) -> Self {
        let mut heap = Self { items };
        // the last parent is at len / 2 - 1. every slot after it is a leaf, a heap of one already
        for i in (0..heap.items.len() / 2).rev() {
            heap.sift_down(i);
        }
        heap
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cmp::Reverse;
    use std::collections::BinaryHeap;

    /// Every parent is at most its children.
    fn is_heap(xs: &[i64]) -> bool {
        (1..xs.len()).all(|i| xs[(i - 1) / 2] <= xs[i])
    }

    /// Pops until the heap is empty.
    fn drain(h: &mut MinHeap) -> Vec<i64> {
        std::iter::from_fn(|| h.pop()).collect()
    }

    #[test]
    fn starts_empty() {
        let mut h = MinHeap::new();
        assert!(h.is_empty());
        assert_eq!((h.pop(), h.peek()), (None, None));
        assert!(h.items().is_empty());
    }

    #[test]
    fn pops_come_out_smallest_first() {
        let mut h = MinHeap::new();
        for x in [5, 3, 8, 1, 9, 2] {
            h.push(x);
        }
        assert_eq!(drain(&mut h), [1, 2, 3, 5, 8, 9]);
    }

    #[test]
    fn keeps_duplicates() {
        let mut h = MinHeap::new();
        for x in [4, 1, 4, 1] {
            h.push(x);
        }
        assert_eq!(drain(&mut h), [1, 1, 4, 4]);
    }

    #[test]
    fn peek_shows_the_top_and_leaves_it() {
        let h = MinHeap::from(vec![3, 1, 2]);
        assert_eq!((h.peek(), h.peek(), h.len()), (Some(1), Some(1), 3));
    }

    #[test]
    fn push_sifts_up_past_bigger_parents() {
        let mut h = MinHeap::from(vec![1, 3, 5, 4, 8, 9, 7]);
        h.push(2);
        assert_eq!(h.items(), [1, 2, 5, 3, 8, 9, 7, 4]);
    }

    #[test]
    fn pop_moves_the_last_item_to_the_top_and_sifts_it_down() {
        let mut h = MinHeap::from(vec![1, 2, 5, 3, 8, 9, 7, 4]);
        assert_eq!(h.pop(), Some(1));
        assert_eq!(h.items(), [2, 3, 5, 4, 8, 9, 7]);
    }

    #[test]
    fn equal_children_the_left_one_moves_up() {
        let mut h = MinHeap::from(vec![1, 3, 3, 7, 8]);
        assert_eq!(h.pop(), Some(1));
        assert_eq!(h.items(), [3, 7, 3, 8]);
    }

    #[test]
    fn build_sifts_down_from_the_last_parent() {
        let cases: [(&[i64], &[i64]); 4] = [
            (&[9, 8, 7, 6, 5, 4, 3, 2, 1], &[1, 2, 3, 6, 5, 4, 7, 8, 9]),
            (&[], &[]),
            (&[7], &[7]),
            // a valid heap is left as it is
            (&[1, 3, 5, 4, 8, 9, 7], &[1, 3, 5, 4, 8, 9, 7]),
        ];
        for (input, want) in cases {
            let h = MinHeap::from(input.to_vec());
            assert_eq!(h.items(), want, "input {input:?}");
        }
    }

    #[test]
    fn every_parent_is_at_most_its_children() {
        // xorshift32 seeded with 7
        let mut state: u32 = 7;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            i64::from(state)
        };
        let mut h = MinHeap::new();
        for _ in 0..100 {
            h.push(next() % 100);
            assert!(is_heap(h.items()));
        }
    }

    #[test]
    fn agrees_with_binary_heap_over_2000_seeded_ops() {
        // 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;
            i64::from(state)
        };
        let mut h = MinHeap::new();
        let mut model = BinaryHeap::new(); // a max-heap, so Reverse makes it give the smallest
        for _ in 0..2000 {
            if next() % 100 == 0 {
                // the model's items, biggest first: the most work for a build
                let mut xs: Vec<i64> = model.iter().map(|&Reverse(x)| x).collect();
                xs.sort_by_key(|&x| Reverse(x));
                h = MinHeap::from(xs);
            } else {
                match next() % 3 {
                    0 => {
                        let x = next() % 100;
                        h.push(x);
                        model.push(Reverse(x));
                    }
                    1 => assert_eq!(h.pop(), model.pop().map(|Reverse(x)| x)),
                    _ => assert_eq!(h.peek(), model.peek().map(|&Reverse(x)| x)),
                }
            }
            assert_eq!(h.len(), model.len());
            assert!(is_heap(h.items()));
        }
        let mut got = h.items().to_vec();
        let mut want: Vec<i64> = model.into_iter().map(|Reverse(x)| x).collect();
        got.sort();
        want.sort();
        assert_eq!(got, want);
    }
}
site/src/visuals/heap/min-heap.ts
/**
 * Binary min-heap: O(1) peek, O(log n) push and pop, O(n) to build from n items. Packed into an array, with item
 * i's children at 2i + 1 and 2i + 2.
 */
export class MinHeap {
  #items: number[] = [];

  /** Build a heap from values in O(n): sift down every parent, the last one first. */
  static from(values: Iterable<number>): MinHeap {
    const h = new MinHeap();
    h.#items = [...values];
    for (let i = Math.floor(h.#items.length / 2) - 1; i >= 0; i--) h.#siftDown(i);
    return h;
  }

  get size(): number {
    return this.#items.length;
  }

  /** The smallest item, left in place. */
  peek(): number | undefined {
    return this.#items[0];
  }

  /** Add x at the end, then swap it up while it's smaller than its parent. */
  push(x: number): void {
    this.#items.push(x);
    this.#siftUp(this.#items.length - 1);
  }

  /** Take out the smallest item: the last item moves to the top and sifts down. */
  pop(): number | undefined {
    const items = this.#items;
    if (items.length === 0) return undefined;
    const top = items[0];
    const last = items.pop()!;
    if (items.length > 0) {
      items[0] = last;
      this.#siftDown(0);
    }
    return top;
  }

  /** The items in array order: slot i is node i of the tree. */
  items(): number[] {
    return [...this.#items];
  }

  // an equal parent stops the climb: only a strictly smaller item swaps up
  #siftUp(i: number): void {
    const items = this.#items;
    while (i > 0) {
      const parent = Math.floor((i - 1) / 2);
      if (items[parent] <= items[i]) return;
      [items[parent], items[i]] = [items[i], items[parent]];
      i = parent;
    }
  }

  // swap down with the smaller child until neither child is smaller. equal children: the left one
  #siftDown(i: number): void {
    const items = this.#items;
    const n = items.length;
    for (;;) {
      const left = 2 * i + 1;
      const right = left + 1;
      let small = i;
      if (left < n && items[left] < items[small]) small = left;
      if (right < n && items[right] < items[small]) small = right;
      if (small === i) return;
      [items[i], items[small]] = [items[small], items[i]];
      i = small;
    }
  }
}
c/algos/min_heap.c
/* binary min-heap: O(1) peek, O(log n) push and pop, O(n) to build from n items. packed into an array, with item i's children at 2i + 1 and 2i + 2. */
#include "min_heap.h"

#include <stdlib.h>
#include <string.h>

bool heap_init(MinHeap *h) {
    h->items = malloc(4 * sizeof *h->items);
    h->len = 0;
    h->cap = h->items ? 4 : 0;
    return h->items != NULL;
}

void heap_free(MinHeap *h) {
    free(h->items);
    h->items = NULL;
    h->len = h->cap = 0;
}

/* doubles the slots until n fit, with one realloc. if it fails, the old block is still there, so
   nothing is lost */
static bool grow_to(MinHeap *h, size_t n) {
    size_t cap = h->cap;
    while (cap < n) cap *= 2;
    if (cap == h->cap) return true;
    int *bigger = realloc(h->items, cap * sizeof *bigger);
    if (!bigger) return false;
    h->items = bigger;
    h->cap = cap;
    return true;
}

static void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

/* an equal parent stops the climb: only a strictly smaller item swaps up */
static void sift_up(MinHeap *h, size_t i) {
    int *items = h->items;
    while (i > 0) {
        size_t parent = (i - 1) / 2;
        if (items[parent] <= items[i]) return;
        swap(&items[parent], &items[i]);
        i = parent;
    }
}

/* swap down with the smaller child until neither child is smaller. equal children: the left one,
   since the right one has to be strictly smaller to take over */
static void sift_down(MinHeap *h, size_t i) {
    int *items = h->items;
    for (;;) {
        size_t left = 2 * i + 1, right = left + 1, small = i;
        if (left < h->len && items[left] < items[small]) small = left;
        if (right < h->len && items[right] < items[small]) small = right;
        if (small == i) return;
        swap(&items[i], &items[small]);
        i = small;
    }
}

bool heap_peek(const MinHeap *h, int *out) {
    if (h->len == 0) return false;
    *out = h->items[0];
    return true;
}

bool heap_push(MinHeap *h, int x) {
    if (!grow_to(h, h->len + 1)) return false;
    h->items[h->len++] = x; /* at the end, then up past bigger parents */
    sift_up(h, h->len - 1);
    return true;
}

bool heap_pop(MinHeap *h, int *out) {
    if (h->len == 0) return false;
    *out = h->items[0];
    /* the last item moves to the top and sifts down. if it was the only one, it lands on itself and
       the sift stops right away */
    h->items[0] = h->items[--h->len];
    sift_down(h, 0);
    return true;
}

bool heap_build(MinHeap *h, const int *values, size_t n) {
    if (!grow_to(h, n)) return false;
    /* memcpy can't take a NULL pointer, even for 0 bytes */
    if (n > 0) memcpy(h->items, values, n * sizeof *values);
    h->len = n;
    /* items n / 2 and up are leaves, heaps of one already. so sift down every parent, the last one
       first: n / 2 - 1 down to 0. i counts one above the parent, since a size_t can't go below 0 to
       end the loop */
    for (size_t i = n / 2; i > 0; i--) sift_down(h, i - 1);
    return true;
}
swift/algos/MinHeap.swift
/// binary min-heap: O(1) peek, O(log n) push and pop, O(n) to build from n items. packed into an array, with item i's children at 2i + 1 and 2i + 2.
/// a struct, since the whole heap is one array: copying the struct copies the heap.
public struct MinHeap {
    /// the items in array order: slot i is node i of the tree
    public private(set) var items: [Int] = []

    public init() {}

    /// builds a heap from values in O(n): sift down every parent, the last one first
    public init<S: Sequence>(_ values: S) where S.Element == Int {
        items = Array(values)
        // slots 0..<count / 2 have children. the rest are leaves, each already a heap of one
        for i in (0..<items.count / 2).reversed() {
            siftDown(i)
        }
    }

    public var count: Int { items.count }

    /// the smallest item, left in place
    public func peek() -> Int? {
        items.first
    }

    /// adds x at the end, then swaps it up while it's smaller than its parent
    public mutating func push(_ x: Int) {
        items.append(x)
        siftUp(items.count - 1)
    }

    /// takes out the smallest item: the last item moves to the top and sifts down
    @discardableResult
    public mutating func pop() -> Int? {
        guard let top = items.first else { return nil }
        let last = items.removeLast()
        if !items.isEmpty {
            items[0] = last
            siftDown(0)
        }
        return top
    }

    // an equal parent stops the climb: only a strictly smaller item swaps up
    private mutating func siftUp(_ start: Int) {
        var i = start
        while i > 0 {
            let parent = (i - 1) / 2
            if items[parent] <= items[i] { return }
            items.swapAt(parent, i)
            i = parent
        }
    }

    // swaps down with the smaller child until neither child is smaller. on a tie the left one moves up:
    // the right child has to be strictly smaller to win
    private mutating func siftDown(_ start: Int) {
        var i = start
        let n = items.count
        while true {
            let left = 2 * i + 1
            let right = left + 1
            var small = i
            if left < n && items[left] < items[small] { small = left }
            if right < n && items[right] < items[small] { small = right }
            if small == i { return }
            items.swapAt(i, small)
            i = small
        }
    }
}
python/algos/min_heap.py
"""binary min-heap: O(1) peek, O(log n) push and pop, O(n) to build from n items. packed into an array, with item i's children at 2i + 1 and 2i + 2."""

from __future__ import annotations

from typing import Iterable


class MinHeap:
    """Ints in a plain list. Every parent is at most its children, so the smallest sits in slot 0."""

    def __init__(self) -> None:
        self._items: list[int] = []  # the tree row by row, top to bottom and left to right

    @classmethod
    def from_values(cls, values: Iterable[int]) -> MinHeap:
        """Build a heap from values in O(n): sift down every parent, the last one first."""
        h = cls()
        h._items = list(values)  # a copy, so the caller's list isn't reordered
        # slots n // 2 and up are leaves, and a leaf is a heap of one already
        for i in range(len(h._items) // 2 - 1, -1, -1):
            h._sift_down(i)
        return h

    def __len__(self) -> int:
        return len(self._items)

    def push(self, x: int) -> None:
        """Add x at the end, then swap it up while it's smaller than its parent."""
        self._items.append(x)
        self._sift_up(len(self._items) - 1)

    def pop(self) -> int:
        """Take out the smallest item: the last item moves to the top and sifts down."""
        if not self._items:
            raise IndexError("pop from an empty heap")
        top = self._items[0]
        last = self._items.pop()  # only the last slot can go without leaving a hole
        if self._items:  # unless that was the only item
            self._items[0] = last
            self._sift_down(0)
        return top

    def peek(self) -> int:
        """Return the smallest item, left in place."""
        if not self._items:
            raise IndexError("peek at an empty heap")
        return self._items[0]

    def items(self) -> list[int]:
        """Return a copy of the items in array order: slot i is node i of the tree."""
        return list(self._items)

    def _sift_up(self, i: int) -> None:
        items = self._items
        while i > 0:
            parent = (i - 1) // 2
            if items[parent] <= items[i]:
                return  # an equal parent stops the climb: only a strictly smaller item swaps up
            items[parent], items[i] = items[i], items[parent]
            i = parent

    def _sift_down(self, i: int) -> None:
        """Swap item i down with its smaller child until neither child is smaller."""
        items = self._items
        n = len(items)
        while True:
            left = 2 * i + 1
            right = left + 1
            small = i
            if left < n and items[left] < items[small]:
                small = left
            # strictly smaller, so when both children are equal the left one moves up
            if right < n and items[right] < items[small]:
                small = right
            if small == i:
                return
            items[i], items[small] = items[small], items[i]
            i = small

pitfalls

variants

practice

how real libraries do it

sources

  1. PriorityQueue.java (opens in a new tab) at jdk-21-ga: a balanced binary heap in an array, the children of queue[n] at queue[2*n+1] and queue[2*(n+1)], O(log(n)) to enqueue and dequeue, and linear time for remove(Object) and contains(Object). its heapify (opens in a new tab) is the algorithm “due to floyd (1964)”, O(size). ↩ ↩2

  2. BinaryHeap (opens in a new tab) in the rust docs: a max-heap, with Reverse for a min-heap. push’s cost is expected O(1), averaged over every ordering of the pushed elements; pop is O(log n). ↩ ↩2 ↩3

  3. heap.go (opens in a new tab) at go1.27.2: the minimum element is the root, at index 0. Init is O(n), Push, Pop, Remove and Fix are O(log n), and Fix restores the order after one element’s value changes. ↩ ↩2

  4. heapq (opens in a new tab) in the python docs: heapify turns a list into a min-heap in place, in linear time, and the _max functions for max-heaps were added in 3.14. ↩ ↩2

  5. heapq.py (opens in a new tab) in cpython 3.15.0: _siftdown moves an item toward the root, _siftup moves it toward the leaves, and the comment before _siftup describes its pop: the smaller child moves up until a leaf, then the leftover item sifts up from there. the item sifted in during a pop tends to be large, so this makes fewer comparisons, and the comment points to an exercise in knuth’s volume 3. ↩ ↩2 ↩3

  6. Heap.swift (opens in a new tab) in swift-collections 1.7.3: a double-ended priority queue, implemented as a min-max heap based on atkinson and others, 1986. a node on an even level is at most all its descendants, and a node on an odd level at least all of its. ↩ ↩2

  7. binary_heap/mod.rs (opens in a new tab) at rust 1.99.1: sift_down_to_bottom takes an element all the way down the heap, then sifts it up into place, which is faster when the element belongs near the bottom. pop (opens in a new tab) moves the last element to the top and calls it. ↩