Data structure · Trees and heaps

Binary heap

A complete binary tree stored in an array, ordered so the smallest (or largest) element is at the root: the standard priority queue.

The derivations, edge cases and exercises are in the lesson Sorted collections and priority queues. Open it full width in the playground.

On this page
  1. The idea
  2. Operations
  3. Invariants
  4. When to use it
  5. Built-in equivalents
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

A min-heap keeps every parent no larger than its children. It does not sort the elements; it only guarantees that the root is the minimum, which is all a priority queue needs.

Because the tree is complete, it fits in an array with no pointers: the children of index i are 2i + 1 and 2i + 2. Push appends and sifts up; pop moves the last element to the root and sifts down. Both walk one root-to-leaf path of length ⌊log₂ n⌋.

Representation. An array in level order; parent(i) = ⌊(i − 1) / 2⌋, children 2i + 1 and 2i + 2.

Operations

Binary heap operations and their complexity
OperationTimeExtra spaceNotes
Peek minO(1)O(1)
PushO(log n)O(1) amortizedSift-up along one path.
Pop minO(log n)O(1)Sift-down along one path.
Heapify n elementsO(n)O(1)Bottom-up sift-down; most nodes are near the leaves.
Search for an arbitrary valueO(n)O(1)

Invariants

What stays true before and after every operation.

  • Heap order: a[parent(i)] ≤ a[i] for every i > 0 (min-heap).
  • Shape: the tree is complete, so the array has no gaps.

When to use it

Use it when

  • You repeatedly need the smallest or largest remaining item: Dijkstra, schedulers, merging sorted streams.
  • You want the top k of a large stream with O(k) memory.

Avoid it when

  • You need sorted iteration or arbitrary lookups (use a search tree or sort once).
  • You need to change or delete arbitrary elements often; that needs an indexed heap.

Built-in equivalents

What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.

Python

heapq

C++

std::priority_queue<T>
  • push / emplace O(log n) comparisons, plus the container's push_back (amortized O(1) for vector)
  • pop O(log n) (at most 2 log₂ n comparisons)
  • top O(1)
  • Construct from a range O(n) (make_heap: at most 3n comparisons)

Step through it

The interactive lab for binary heap: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

The binary min-heap in four languages, each checked against one shared fixture of heapify, push, pop and peek sequences (including the exact heap array and errors on an empty heap), and 500 random operation sequences compared with PriorityQueue, heapq, java.util.PriorityQueue and std::priority_queue.

namespace Bekadan.Dsa.Examples.Heaps;
 
/// <summary>
/// Array-backed binary min-heap. Parent of i: (i - 1) / 2; children: 2i + 1, 2i + 2.
/// Push and Pop are O(log n), Peek is O(1), building from n items is O(n).
/// </summary>
public sealed class BinaryHeap<T>
{
    private readonly List<T> _items;
    private readonly Comparison<T> _compare;
 
    public BinaryHeap(Comparison<T>? compare = null) : this([], compare)
    {
    }
 
    /// <summary>Builds a heap from existing items with bottom-up heapify.</summary>
    public BinaryHeap(IEnumerable<T> items, Comparison<T>? compare = null)
    {
        _items = [.. items];
        _compare = compare ?? Comparer<T>.Default.Compare;
        for (int i = _items.Count / 2 - 1; i >= 0; i--) // indices Count/2 and up are leaves
            SiftDown(i);
    }
 
    public int Count => _items.Count;
 
    /// <summary>The heap array, index 0 first (for tests and teaching).</summary>
    public IReadOnlyList<T> Items => _items;
 
    public void Push(T value)
    {
        _items.Add(value); // the next free slot keeps the tree complete
        int i = _items.Count - 1;
        while (i > 0)
        {
            int parent = (i - 1) / 2;
            if (_compare(_items[i], _items[parent]) >= 0)
                break; // not smaller than its parent: done
            (_items[i], _items[parent]) = (_items[parent], _items[i]);
            i = parent;
        }
    }
 
    public T Peek()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The heap is empty.");
        return _items[0];
    }
 
    public T Pop()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The heap is empty.");
        T top = _items[0];
        int last = _items.Count - 1;
        _items[0] = _items[last]; // the last element fills the hole at the root
        _items.RemoveAt(last);
        if (_items.Count > 0)
            SiftDown(0);
        return top;
    }
 
    private void SiftDown(int i)
    {
        while (true)
        {
            int child = 2 * i + 1;
            if (child >= _items.Count)
                return; // a leaf
            if (child + 1 < _items.Count && _compare(_items[child + 1], _items[child]) < 0)
                child++; // the smaller child (the left one on ties)
            if (_compare(_items[child], _items[i]) >= 0)
                return; // not larger than its children: done
            (_items[i], _items[child]) = (_items[child], _items[i]);
            i = child;
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Heaps/BinaryHeap.cs

"""Array-backed binary min-heap.
 
Parent of i: (i - 1) // 2; children: 2i + 1 and 2i + 2. push and pop are
O(log n), peek is O(1), building from n items is O(n). The standard library's
heapq module offers the same operations as functions on a plain list.
"""
 
from collections.abc import Iterable
from typing import Generic, TypeVar
 
T = TypeVar("T")
 
 
class BinaryHeap(Generic[T]):
    def __init__(self, items: Iterable[T] = ()) -> None:
        """Builds a heap from existing items with bottom-up heapify."""
        self._items: list[T] = list(items)
        for i in range(len(self._items) // 2 - 1, -1, -1):  # indices len // 2 and up are leaves
            self._sift_down(i)
 
    def __len__(self) -> int:
        return len(self._items)
 
    def items(self) -> list[T]:
        """A copy of the heap array, index 0 first (for tests and teaching)."""
        return list(self._items)
 
    def push(self, value: T) -> None:
        a = self._items
        a.append(value)  # the next free slot keeps the tree complete
        i = len(a) - 1
        while i > 0:
            parent = (i - 1) // 2
            if not a[i] < a[parent]:
                break  # not smaller than its parent: done
            a[i], a[parent] = a[parent], a[i]
            i = parent
 
    def peek(self) -> T:
        if not self._items:
            raise IndexError("peek from an empty heap")
        return self._items[0]
 
    def pop(self) -> T:
        a = self._items
        if not a:
            raise IndexError("pop from an empty heap")
        top = a[0]
        last = a.pop()
        if a:
            a[0] = last  # the last element fills the hole at the root
            self._sift_down(0)
        return top
 
    def _sift_down(self, i: int) -> None:
        a = self._items
        while True:
            child = 2 * i + 1
            if child >= len(a):
                return  # a leaf
            if child + 1 < len(a) and a[child + 1] < a[child]:
                child += 1  # the smaller child (the left one on ties)
            if not a[child] < a[i]:
                return  # not larger than its children: done
            a[i], a[child] = a[child], a[i]
            i = child

Tested on CPython 3.14.0 · examples/python/dsa_examples/binary_heap.py

package dev.bekadan.dsa.heaps;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
 
/**
 * Array-backed binary min-heap (with respect to the comparator). Parent of i:
 * (i - 1) / 2; children: 2i + 1, 2i + 2. push and pop are O(log n), peek is
 * O(1), building from n items is O(n).
 */
public final class BinaryHeap<T> {
    private final List<T> items;
    private final Comparator<? super T> comparator;
 
    public BinaryHeap(Comparator<? super T> comparator) {
        this(List.of(), comparator);
    }
 
    /** Builds a heap from existing items with bottom-up heapify. */
    public BinaryHeap(Collection<? extends T> initial, Comparator<? super T> comparator) {
        this.items = new ArrayList<>(initial);
        this.comparator = comparator;
        for (int i = items.size() / 2 - 1; i >= 0; i--) { // indices size/2 and up are leaves
            siftDown(i);
        }
    }
 
    public int size() {
        return items.size();
    }
 
    /** The heap array, index 0 first (for tests and teaching). */
    public List<T> items() {
        return Collections.unmodifiableList(items);
    }
 
    public void push(T value) {
        items.add(value); // the next free slot keeps the tree complete
        int i = items.size() - 1;
        while (i > 0) {
            int parent = (i - 1) / 2;
            if (comparator.compare(items.get(i), items.get(parent)) >= 0) {
                break; // not smaller than its parent: done
            }
            Collections.swap(items, i, parent);
            i = parent;
        }
    }
 
    public T peek() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The heap is empty.");
        }
        return items.get(0);
    }
 
    public T pop() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The heap is empty.");
        }
        T top = items.get(0);
        T last = items.remove(items.size() - 1);
        if (!items.isEmpty()) {
            items.set(0, last); // the last element fills the hole at the root
            siftDown(0);
        }
        return top;
    }
 
    private void siftDown(int i) {
        while (true) {
            int child = 2 * i + 1;
            if (child >= items.size()) {
                return; // a leaf
            }
            if (child + 1 < items.size() && comparator.compare(items.get(child + 1), items.get(child)) < 0) {
                child++; // the smaller child (the left one on ties)
            }
            if (comparator.compare(items.get(child), items.get(i)) >= 0) {
                return; // not larger than its children: done
            }
            Collections.swap(items, i, child);
            i = child;
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/heaps/BinaryHeap.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <stdexcept>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// Array-backed binary min-heap (with respect to Less). Parent of i: (i - 1) / 2;
// children: 2i + 1, 2i + 2. push and pop are O(log n), top is O(1), building from
// n items is O(n). Note: std::priority_queue with std::less is a MAX-heap.
 
template <typename T, typename Less = std::less<>>
class BinaryHeap {
public:
    explicit BinaryHeap(Less less = {}) : less_(std::move(less)) {}
 
    // Builds a heap from existing items with bottom-up heapify.
    explicit BinaryHeap(std::vector<T> items, Less less = {}) : items_(std::move(items)), less_(std::move(less)) {
        for (std::size_t i = items_.size() / 2; i-- > 0;)  // i = size/2 - 1 down to 0; the rest are leaves
            sift_down(i);
    }
 
    [[nodiscard]] std::size_t size() const noexcept { return items_.size(); }
    [[nodiscard]] bool empty() const noexcept { return items_.empty(); }
 
    // The heap array, index 0 first (for tests and teaching).
    [[nodiscard]] const std::vector<T>& items() const noexcept { return items_; }
 
    void push(T value) {
        items_.push_back(std::move(value));  // the next free slot keeps the tree complete
        std::size_t i = items_.size() - 1;
        while (i > 0) {
            const std::size_t parent = (i - 1) / 2;
            if (!less_(items_[i], items_[parent]))
                break;  // not smaller than its parent: done
            std::swap(items_[i], items_[parent]);
            i = parent;
        }
    }
 
    [[nodiscard]] const T& top() const {
        if (items_.empty())
            throw std::underflow_error("the heap is empty");
        return items_.front();
    }
 
    T pop() {
        if (items_.empty())
            throw std::underflow_error("the heap is empty");
        T result = std::move(items_.front());
        if (items_.size() > 1)
            items_.front() = std::move(items_.back());  // the last element fills the hole at the root
        items_.pop_back();
        if (!items_.empty())
            sift_down(0);
        return result;
    }
 
private:
    void sift_down(std::size_t i) {
        while (true) {
            std::size_t child = 2 * i + 1;
            if (child >= items_.size())
                return;  // a leaf
            if (child + 1 < items_.size() && less_(items_[child + 1], items_[child]))
                ++child;  // the smaller child (the left one on ties)
            if (!less_(items_[child], items_[i]))
                return;  // not larger than its children: done
            std::swap(items_[i], items_[child]);
            i = child;
        }
    }
 
    std::vector<T> items_;
    Less less_;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/binary_heap.hpp

Learn more

Lessons

Problems, patterns and exercises

References