All chapters[•]Data StructuresChapter 08
Data Structures · Chapter 8

Heaps and Priority QueuesData Structures · Chapter 8

An emergency room does not treat patients in the order they walk in, and a computer does not run its tasks in the order they arrive. This chapter builds the structure behind "give me the most urgent one": the priority queue, and the heap, a tree stored in a plain array that keeps only the smallest entry on top and repairs itself in about log n steps. The same idea builds a heap from n entries in O(n) steps and sorts an array in place.

Instructors: Boxi Yu · Yintong Huo · Python and Java versions (switch at the top) · Every program here has been run, and every output shown is the real output. · All chapters

A min-heap as a tree and as an array

Type a number or press Insert to add it to a min-heap: the tree and the array below it are shown side by side, the new entry climbs and every swap is highlighted in both views; Remove min takes the root, moves the last entry up and lets it sink. A readout counts the comparisons and swaps of each operation.

Why this matters

about 90–120 minutes (4 videos of 8–10 minutes plus the exercises).

"The most urgent first" is everywhere

Operating systems pick the next process, simulators pick the next event, Dijkstra's shortest paths (chapter 9) pick the next vertex, and a search for the k best results keeps the k best so far: all of them need a collection with a fast insert and a fast "take out the smallest".

Promise only what you need

A priority queue promises one thing, that the smallest key comes out first, not that the entries are sorted. That weaker promise is why a heap makes both insert and remove-min cost about log n, where a sorted list or an unsorted list pays about n for one of them.

A tree needs no pointers when it is complete

Storing the tree level by level in an array turns "parent" and "child" into index arithmetic; the same layout gives a heap built in O(n) and an in-place sort with a guaranteed O(n log n), and it is the reason the standard libraries' priority queues are arrays.

5 parts

Four videos with their notes, then the summary and practice. Read them in order.

01

The priority queue ADT

A priority queue stores entries, each a key (the priority) and a value, and promises only that remove_min returns the entry with the smallest key. An unsorted list and a sorted list both implement it, but each pays about n steps for one of the two operations. A heap, which is deliberately not sorted, pays about log n for both.

entrykey and valueinsertminremove_minunsorted listsorted listheapheapqPriorityQueue
Open →
02

Heap: up-heap and down-heap

A heap is a complete binary tree stored in an array with one local rule: no child is smaller than its parent. Insert adds the entry at the end and climbs (up-heap); remove min moves the last entry to the root and sinks it (down-heap). The tree has only about log₂ n levels, so both take about log n steps.

complete binary treeheap orderindex formulasup-heapdown-heapO(log n)invariant
Open →
03

Bottom-up heap construction

You already have n entries in an array and want a heap. Inserting them one by one costs up to n log n, but there is a cheaper way: start at the last entry that has a child and sink every entry in turn, back to the root. Half of the entries are leaves and cost nothing, and adding up what the others can cost gives about n, never more than 2n comparisons.

heapifybottom-uplast internal nodesum of heightsO(n)build versus insert
Open →
04

Heap sort

A heap gives its smallest entry in about log n steps; take entries out one by one and they come out in order. Heap sort does this inside the array it was given: build a max-heap, then repeatedly swap the root with the last entry of the heap, shrink the heap by one and sink the new root. The sorted part grows at the back while the heap shrinks at the front: O(n log n) in the worst case, O(1) extra memory, and not stable.

heap sortmax-heapin placeO(n log n) worst casenot stablecomparison with merge sort and quicksort
Open →
05

Summary and practice

A one-page map of the chapter, five self-check questions, ten exercises with solutions, and a way to test claims an AI makes about complexity.

self-checkexercises
Open →

How to use these notes

Watch · Predict · Step through · Practise

STEP 1

Watch

Each part starts with its video, 8–10 minutes, in Python or Java.

STEP 2

Predict

Answer the amber Predict box before you open the answer.

STEP 3

Step through

The interactive demos are being added; each one is described where it will appear.

STEP 4

Practise

Finish with the self-check and the exercises, with templates in your language.