Log inStart free
LESSON 3.04 · 6 STAGES · 2 CONTROLS · 3 CHECKSPRO · PREVIEW

Heaps and priority queues

Watch a heap keep the smallest priority on top with a few swaps.


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 2 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 3.04 · HEAP BAY7 ITEMS · 3 LEVELS · INDEXES 0–6
01
Stage 1 of 6 · Array as tree
A binary heap keeps a complete binary tree in an array. Index i has children 2i + 1 and 2i + 2.
Explain it simply

The heap keeps 7 numbers in one row, called an array. Read the row level by level, and you get the tree below it. The root sits at index 0. The children of index i sit at two i plus one and two i plus two. So the tree needs no pointers, only this sum.

The array holds 2, 5, 4, 11, 7, 9, 8 at indexes 0 to 6. The tree shows the same items on 3 levels.

item (its priority)index, parent–child linkbroken ordermoving item, popped itemfree slot
arraytreeArray as treelevel 0 · 0level 1 · 1–2level 2 · 3–6level 3 · 7–1401234567pushpop →25411798i = 1: item 5left 2·1+1 = 3 → 11right 2·1+2 = 4 → 7parent ⌊(1−1)/2⌋ = 0 → 2level 1 holds 1–2arraytreeArray as treelevel 0 · 0level 1 · 1–2level 2 · 3–6level 3 · 7–1401234567pushpop →25411798i = 1: item 5left 2·1+1 = 3 → 11right 2·1+2 = 4 → 7parent ⌊(1−1)/2⌋ = 0 → 2level 1 holds 1–2
Toy: 7 priorities pushed as 5, 2, 9, 11, 7, 8, 4 · one push, one pop · arrays match Python's heapq
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
left(i)=2i+1,right(i)=2i+2,parent(i)=⌊(i−1)/2⌋\mathrm{left}(\sy{i}{param}{i}) = 2\sy{i}{param}{i} + 1,\quad \mathrm{right}(\sy{i}{param}{i}) = 2\sy{i}{param}{i} + 2,\quad \mathrm{parent}(\sy{i}{param}{i}) = \lfloor (\sy{i}{param}{i} - 1)/2 \rfloor
left(1)=3→11,  right(1)=4→7,  parent(1)=0→2\mathrm{left}(1) = 3 \to 11,\ \ \mathrm{right}(1) = 4 \to 7,\ \ \mathrm{parent}(1) = 0 \to 2

The children of index i sit at 2i + 1 and 2i + 2.

Common mix-ups

MYTHA heap keeps its array sorted.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01If the new priority is 10, which item does pop return?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 2 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.