Wiki
Advanced13 min read

Heaps and priority queues

A complete tree stored in an array keeps the minimum at the root and both insert and extract in logarithmic time.

A binary search tree keeps everything ordered. Often you do not need that — you only need to know the smallest element, then remove it and know the next smallest. A heap provides exactly that weaker guarantee for a fraction of the bookkeeping, and it needs no pointers at all: it fits in a flat array.

Weak order is enough

In a heap, every parent is smaller than its children, but siblings and cousins have no relation to each other. That is all that is required for the minimum to sit at the root. The weaker invariant means insert and extract only walk a single root-to-leaf path instead of rebalancing a tree.

Insert values and extract the minimum below. Each operation really sifts through the array; the tree drawn is just the same array read by index.

Insert and extract-min — the smallest always floats to the root

2i=05i=17i=29i=36i=48i=5
257968

—

The heap property is local: every parent is smaller than its children, which is enough for the minimum to be at index 0 but not enough for the array to be sorted. Both insert and extract-min do at most log₂ n swaps, because each step halves the distance to the root or to a leaf.

The array is the tree

A heap is a complete binary tree — every level full except possibly the last, filled left to right — which lets it be stored contiguously with no pointers:

  • index ii has children at 2i+12i+1 and 2i+22i+2;
  • index ii has its parent at ⌊(i−1)/2⌋\lfloor (i-1)/2 \rfloor.

Complete means the array has no gaps, so the height is always ⌊log⁡2n⌋\lfloor \log_2 n \rfloor — the tree is balanced by construction. That is what a heap gives up the BST's fully sorted order to gain.

Sift up and sift down

Two procedures maintain the property:

  • Sift up after appending: while the new element is smaller than its parent, swap them. At most one path up, so O(log⁡n)O(\log n).
  • Sift down after removing the root: move the last leaf to the root, then repeatedly swap it with the smaller child until both children are larger. Again O(log⁡n)O(\log n).
import heapq
 
heap = []
heapq.heappush(heap, 5)
heapq.heappush(heap, 2)
smallest = heapq.heappop(heap)   # 2

The array heap is the heap; heapq provides the operations. There is no separate class.

Priority queues

The usual reason to reach for a heap is a priority queue: a queue that removes the item with the highest priority rather than the oldest. Because both operations are O(log⁡n)O(\log n), scheduling many tasks costs O(nlog⁡n)O(n \log n) overall instead of the O(n2)O(n^2) a repeatedly re-sorted list would cost. Dijkstra's shortest-path algorithm and event simulation both run on this structure.

Heap is not sorted

The array is only partially ordered. Iterating it does not give sorted output, and heap[1] is the smaller of the root's two children but not necessarily the second-smallest element overall. To get sorted order, repeatedly pop.

Illustrative vs real

The simulator keeps the heap small enough to draw, and shows the array and its tree side by side. Real heaps hold millions of entries and are often built bottom-up in O(n)O(n) from an unsorted array. The index arithmetic and the two sift routines are identical; only the scale changes.

Check yourself

Eduspheria wiki · Programming & Data Structures, Data structures

0 / 5 answered

  1. 1In an array-backed min-heap, where is the smallest element always found?
    Multiple choice
  2. 2For a node at index 2 in an array heap, what is the 0-based index of its left child?
    Numeric answer
  3. 3A heap's underlying array is fully sorted.
    True / false
  4. 4What are the costs of push and pop on a binary heap of size n?
    Multiple choice
  5. 5Which algorithm for shortest paths in a weighted graph relies on a priority queue?
    Short answer

From the exam paper

Modeled on NITJ AI-507, End-Sem December 2024

0 / 5 answered

  1. 1The 0-indexed array 94, 24, 55, 22, 17, 20, 7, 10, 12, 16, 11, 14, 105 violates the max-heap property at one position. What is the minimum number of interchanges needed to turn it into a max-heap?
    interchanges
    Numeric answer
  2. 2After restoring the max-heap property to 94, 24, 55, 22, 17, 20, 7, 10, 12, 16, 11, 14, 105, which array results?
    Multiple choice
  3. 3The values 5, 3, 17, 10, 85, 2, 19, 6, 22 are inserted one at a time, in that order, into an initially empty min-heap. Which array represents the resulting heap?
    Multiple choice
  4. 4In the min-heap array 2, 5, 3, 6, 85, 17, 19, 10, 22, what value is stored at index 1?
    Numeric answer
  5. 5Building a heap by inserting n elements one at a time costs O(n log n), because each sift-up follows a single path of logarithmic length.
    True / false

Where next: hash tables — O(1) lookup without maintaining any order at all.