data structurestrees
heap
a tree packed into an array, smallest item on top. it's how a priority queue works.
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
- 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
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
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
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
- -
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.
tap a slot.
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
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.
- the leaves are heaps already. the back half of the array has no children. so start at the last parent, n / 2 - 1, and sift each parent down, the last one first. by the time a parent sifts down, both subtrees under it are heaps, so one sift down is all it needs
- most items are near the bottom. half the items are leaves and never move. a quarter can sink one level, an eighth two. a push goes the other way: the many items at the bottom are the ones with the farthest to climb
- the total stays under n. the worst a build can do is n minus the number of 1s in n written in binary, so always fewer than n swaps. for 1023 items that’s 1013, against 8194 pushing them one at a time. on 1023 random numbers, the build took 755 swaps and one push at a time 1252
- an old idea. java’s
PriorityQueuebuilds this way, and its source credits the algorithm to floyd, 19641
complexity
| operation | worst | average |
|---|---|---|
| peek | O(1) | O(1) |
| push | O(log n) | O(1) |
| pop | O(log n) | O(log n) |
| build from n | O(n) | O(n) |
| find an item | O(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.
// 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
}
}//! 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);
}
}/**
* 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;
}
}
}/* 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;
}/// 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
}
}
}"""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 = smallpitfalls
- off-by-one parents. with the root at index 0, the children of i are at 2i + 1 and 2i + 2, and the parent at (i - 1) / 2. books that put the root at index 1 use 2i, 2i + 1 and i / 2. mix the two and the tree comes apart
- swapping with the wrong child. sift down has to swap with the smaller child. swap with the bigger one and the smaller child ends up under a bigger parent
- expecting it sorted. only the top is in order. walking the array gives the items in no useful order. to get them sorted, pop them one by one: that’s heap sort
- changing a priority in place. an item whose priority changes while it’s in the heap is in the wrong spot. go’s
heap.Fixsifts it back,3 or push a fresh copy and skip stale ones as they come out - max or min. rust’s
BinaryHeapis a max-heap: wrap items inReversefor a min-heap.2 python’sheapqis a min-heap, with functions for max-heaps since 3.144 - heapq’s names run backwards. in python’s source,
_siftdownmoves an item toward the root and_siftupmoves it toward the leaves: the opposite of most books5
variants
- max-heap. flip the comparison and the biggest item is on top. heap sort uses one, so it can move the biggest to the back of the array
- d-ary heap. d children per node instead of 2. fewer levels make pushes cheaper, but a pop compares d children at each step
- min-max heap. levels alternate between min order and max order, so the smallest and the biggest are both a peek away. swift-collections’
Heapis one, after atkinson and others, 19866 - bottom-up pop. python’s
heapqand rust’sBinaryHeappop without comparing the moved item on the way down. at each level the child that belongs higher moves up (the smaller one in a min-heap, the bigger in rust’s max-heap), all the way to a leaf, and the leftover item goes there and sifts up. it saves comparisons, since that item usually belongs near the bottom anyway5,7 - decrease-key. dijkstra’s algorithm lowers the priority of items already in the heap. an indexed heap tracks where each item sits, so it can sift one up in place
practice
- kth largest element in an array (opens in a new tab): a min-heap that keeps the k biggest
- last stone weight (opens in a new tab): a max-heap, popped two at a time
- top k frequent elements (opens in a new tab): count, then keep the k most frequent in a heap
- merge k sorted lists (opens in a new tab): a heap of the k list heads
- find median from data stream (opens in a new tab): a max-heap and a min-heap, one for each half
how real libraries do it
- python.
heapqis functions over a plain list: a min-heap,heapifyin linear time,4 and a pop that walks the smaller child up to a leaf first5 - java.
PriorityQueueis a binary heap in an array: O(log n) to add or poll, linear time forremove(Object)andcontains1 - go.
container/heapis an interface: your type suppliesLen,Less,Swap,PushandPop, and the package keeps the order.Initis O(n), andFixrepairs one changed item3 - rust.
BinaryHeapis a max-heap. push is O(1) expected, averaged over the orders items arrive in, and pop is O(log n)2 - swift. no heap in the standard library. swift-collections’
Heapis a min-max heap6
sources
-
PriorityQueue.java (opens in a new tab) at jdk-21-ga: a balanced binary heap in an array, the children of
queue[n]atqueue[2*n+1]andqueue[2*(n+1)], O(log(n)) to enqueue and dequeue, and linear time forremove(Object)andcontains(Object). itsheapify(opens in a new tab) is the algorithm “due to floyd (1964)”, O(size). ↩ ↩2 -
BinaryHeap (opens in a new tab) in the rust docs: a max-heap, with
Reversefor 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 -
heap.go (opens in a new tab) at go1.27.2: the minimum element is the root, at index 0.
Initis O(n),Push,Pop,RemoveandFixare O(log n), andFixrestores the order after one element’s value changes. ↩ ↩2 -
heapq (opens in a new tab) in the python docs:
heapifyturns a list into a min-heap in place, in linear time, and the_maxfunctions for max-heaps were added in 3.14. ↩ ↩2 -
heapq.py (opens in a new tab) in cpython 3.15.0:
_siftdownmoves an item toward the root,_siftupmoves it toward the leaves, and the comment before_siftupdescribes 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 -
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
-
binary_heap/mod.rs (opens in a new tab) at rust 1.99.1:
sift_down_to_bottomtakes 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. ↩