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/moEXPLAINER · 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
Toy: 7 priorities pushed as 5, 2, 9, 11, 7, 8, 4 · one push, one pop · arrays match Python's heapq
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
The children of index i sit at 2i + 1 and 2i + 2.
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.