Heaps · push/pop O(log n); heapify O(n)

Binary heap

An array-backed min-heap: push with sift-up, pop with sift-down, heapify.

The full explanation, derivation and practice are in the lesson Heaps and priority queues.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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