Menu
Coddy logo textTech

Heap (Binary Heap)

Last updated

A binary heap is a complete binary tree that keeps the smallest (min-heap) or largest (max-heap) value at the root. This visualization is a min-heap: every parent is less than or equal to its children. To add a value you append it at the next open slot, then "sift it up" - swapping it with its parent while it's smaller - until the heap property holds again. Press play above to watch each new value bubble up to its place.

Because a heap is a complete tree, it's stored compactly in an array: node i's children are at 2i+1 and 2i+2. Insert and remove-min are O(log n) (one path from root to leaf), while peeking at the min is O(1) - which is exactly what a priority queue needs.

Time & space complexity

OperationComplexityNotes
Peek min/maxO(1)It's always the root
Insert (push)O(log n)Sift up one path
Remove min/maxO(log n)Sift down one path
Build heapO(n)Heapify all at once
SpaceO(n)Array-backed, no pointers

Step by step (push)

StepWhat happens
1Append the new value at the end (next open leaf).
2Compare it with its parent.
3If it's smaller (min-heap), swap it up.
4Repeat until it's no longer smaller than its parent, or reaches the root.

Worked example

Building a min-heap by pushing [5, 3, 8, 1, 4] one value at a time:

PushArray after sift-upAction
5[5]First value becomes the root.
3[3, 5]3 < parent 5, so swap it up to the root.
8[3, 5, 8]8 > parent 5, so it stays as a leaf.
1[1, 3, 8, 5]1 < parent 5, swap; then 1 < parent 3, swap to the root.
4[1, 3, 8, 5, 4]4 > parent 3, so it stays; the min 1 remains at the root.

When to use a heap

Use it whenAvoid it when
You repeatedly need the smallest or largest item from a changing set.You need to search for arbitrary values, not just the extreme - use a BST or hash set.
You're implementing a priority queue for Dijkstra, A*, or a scheduler.You need the data kept in fully sorted order at all times.
You want O(log n) insert and remove-min with a compact array layout.You need fast lookup or removal of a specific (non-root) element.
You need to merge a stream of items and pull them out by priority.The dataset is tiny and a linear scan is simpler and fast enough.

Heap (Priority Queue) code

A clean, runnable Heap (Priority Queue) implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Heap (Priority Queue) code in Python

Python
1class MinHeap:2    def __init__(self):3        self.data = []4
5    def push(self, value):6        # Append at the end, then bubble up to restore order7        self.data.append(value)8        i = len(self.data) - 19        while i > 0:10            parent = (i - 1) // 211            if self.data[parent] <= self.data[i]:12                break13            self.data[i], self.data[parent] = self.data[parent], self.data[i]14            i = parent15
16    def pop(self):17        # Move the last leaf to the root, then sift it down18        top = self.data[0]19        last = self.data.pop()20        if self.data:21            self.data[0] = last22            self._sift_down(0)23        return top24
25    def _sift_down(self, i):26        n = len(self.data)27        while True:28            smallest = i29            left, right = 2 * i + 1, 2 * i + 230            if left < n and self.data[left] < self.data[smallest]:31                smallest = left32            if right < n and self.data[right] < self.data[smallest]:33                smallest = right34            if smallest == i:35                return36            self.data[i], self.data[smallest] = self.data[smallest], self.data[i]37            i = smallest38
39
40heap = MinHeap()41for value in [5, 3, 8, 1, 9, 2]:42    heap.push(value)43
44print("Heap array:     ", heap.data)45print("Popped in order:", [heap.pop() for _ in range(6)])
Run this code in the Python Playground

Heap FAQ

What is a heap used for?
Heaps implement priority queues, which power Dijkstra's shortest-path algorithm, task schedulers, and event simulations. They're also the engine behind heapsort. Any time you repeatedly need the smallest or largest item from a changing set, a heap is the tool.
What is the difference between a heap and a binary search tree?
Both are binary trees, but a BST keeps a full left-to-right sorted order (enabling ordered search), while a heap only guarantees the parent-child relationship (min or max at the root). A heap gives O(1) access to the extreme value; a BST gives O(log n) search for any value.
Why is a heap stored in an array?
Because a heap is always a complete binary tree, its nodes map perfectly onto array indices: the children of index i are at 2i+1 and 2i+2, and the parent is at (i-1)/2. This avoids storing child pointers and gives excellent cache performance.
Is a heap the same as a sorted array?
No. A heap only guarantees that each parent is smaller (min-heap) or larger (max-heap) than its children, so siblings and cousins are in no particular order. A sorted array is fully ordered but costs O(n) to insert into, whereas a heap inserts in O(log n) while still giving instant access to the extreme value.
When should I use a heap instead of just sorting an array?
Reach for a heap when the data keeps changing and you only ever need the current minimum or maximum - inserting and popping cost O(log n) each, versus re-sorting the whole array. If you have a static dataset and want every element in order, a single O(n log n) sort is simpler and often faster.
Does building a heap from n items take O(n log n)?
Not if you build it all at once. Inserting n items one by one is O(n log n), but the bottom-up heapify that sifts down from the last parent to the root runs in O(n) overall, because most nodes are near the bottom and sift down only a short distance.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED