← Course home

Lookup and priority · Lesson 32 of 52

Heap operations

Trace heap insertion, removal, heap construction, and heapsort using array indexes.

Full lessonAbout 10 min

You will learn to trace sift-down and heap construction and derive heapsort's time and extra-space costs.

Recommended first: Arrays and Python sequence costs.

On this page 6 sections

The idea

heapsort on [3, 1, 4, 2] returns [1, 2, 3, 4].

A complete tree fills every level except possibly the last, and that last level fills from the left. A binary heap stores a complete tree in an array. Python's heapq is this structure as a min-heap. heappop returns the smallest item. For a max-heap, every parent is ≥ its children, so the largest key is at index 0. The children of index i are 2i + 1 and 2i + 2. heapify starts at the last parent and sifts that item down until the invariant holds. On [3, 1, 4, 2] the last parent is index 1. Sifting swaps 1 with 2, leaving [3, 2, 4, 1]. Sifting the root then swaps 3 with 4, leaving [4, 2, 3, 1]. heapsort extracts the root until the array is sorted. The library returns [1, 2, 3, 4].

A worked trace

StepStateWhat changed
siftheap = [3, 2, 4, 1]Sift-down at index 1 leaves [3, 2, 4, 1].
siftheap = [4, 2, 3, 1]Sift-down at index 0 leaves [4, 2, 3, 1].
extractheap = [3, 2, 1, 4]Extract moves the next root. The array is [3, 2, 1, 4].
extractheap = [2, 1, 3, 4]Extract moves the next root. The array is [2, 1, 3, 4].
extractheap = [1, 2, 3, 4]Extract moves the next root. The array is [1, 2, 3, 4].

Why it is correct

Sift-down restores the invariant in one subtree when both children are already heaps. It swaps the parent with the larger child when the parent is smaller, then repeats. Each swap moves the violation down, and a leaf has no child to violate. heapify can start at the last parent because every index after that is a leaf, and a leaf is already a heap. The extraction loop removes the current maximum and sifts the item that was moved into the root, so the next maximum surfaces. Writing extracted maxima from the end of the array backward produces ascending order.

A common mistake

heapify is linear. Repeating extract-max is the n log n part.

What it costs

heapify is Θ(n). The sift at a node is proportional to its height, and the sum of heights in a complete tree is less than 2n. Each of the n extractions then sifts a prefix of height Θ(log n), so heapsort is Θ(n log n) time. The heap reuses the input array, so extra memory is O(1). The sort is not stable. A priority queue uses the same sift for insert and extract-min, each Θ(log n). Which is the right cost when you need the next extreme key and not the full sorted order.

Run it

python
from bitsandbytes.heaps.heapsort import heapsortprint(heapsort([3, 1, 4, 2]))# prints: [1, 2, 3, 4] 

Practice and next step

Open Priority queues next. A priority queue is that heap when you also need to lower a key you already pushed.

Implementation and tests Optional reference

Library code 1

  • bitsandbytes.heaps.heapsort

Use these references to compare the explanation with repository code and tests. A test link means it imports a lesson symbol; it does not by itself claim complete behavior coverage.

Step-by-step trace

Heapify [3, 1, 4, 2]

Children of index i are 2i + 1 and 2i + 2. heapify sifts from the last parent down to the root. heapsort then extracts until the array is sorted ascending.

heap
[3, 2, 4, 1]

State

  1. 03comparing
  2. 12comparing
  3. 24comparing
  4. 31comparing

Sift-down at index 1 leaves [3, 2, 4, 1].

Practice with feedback

Check your understanding

Try each checkpoint before revealing the feedback. Ask for a hint when you need one. Answers and hints stay in this browser when local storage is available.

1Index 1 in [3, 8, 1, 9, 4, 2] has children at 3 and 4. Which child is larger?
2Which value belongs in the named cell?

Fill sift, row State, cell 0.

Progress is never sent to an account or synced to another device. If local storage is blocked, choices last only until you leave this page.