🖨️ Printing Instructions: Press Ctrl/Cmd + P and select "Save as PDF".
1

Heaps, Heapsort, and Priority Queues

2

Learning Goals

3

Background Review: Trees & Complexity

4

What is a Tree?

5

Tree Terminology

6

What is a Binary Tree?

7

Types of Binary Trees

8

Why Complete Binary Trees Matter

9

Quick Review: Big-O Notation

10

Why $\log n$ Appears Often

11

The Heap Data Structure

12

What is a Heap?

13

Binary Tree Concepts

14

Array Representation (1-indexed)

15

Array Representation (0-indexed)

16

Why Two Conventions?

17

Array Representation: Visual Example

18

Index Formulas: Quick Reference

19

Heap Property

20

Heap vs. Sorted Array

21

Maintaining the Heap

22

Quick Review: Recursion

23

Max-Heapify

24

Max-Heapify: Intuition

25

Max-Heapify(A, i) — 1-indexed

l = 2*i          // left child
r = 2*i + 1      // right child
largest = i
if l <= heap_size and A[l] > A[largest]
  largest = l
if r <= heap_size and A[r] > A[largest]
  largest = r
if largest != i
  swap A[i] with A[largest]
  Max-Heapify(A, largest)
26

Max-Heapify(A, i) — 0-indexed

l = 2*i + 1      // left child
r = 2*i + 2      // right child
largest = i
if l < heap_size and A[l] > A[largest]
  largest = l
if r < heap_size and A[r] > A[largest]
  largest = r
if largest != i
  swap A[i] with A[largest]
  Max-Heapify(A, largest)
27

Heapify Trace

28

Building a Heap

29

Build-Max-Heap

30

Why Bottom-Up?

31

Build-Max-Heap(A) — 1-indexed

heap_size = A.length
for i = floor(A.length / 2) down to 1
  Max-Heapify(A, i)
32

Build-Max-Heap(A) — 0-indexed

heap_size = A.length
for i = floor(A.length / 2) - 1 down to 0
  Max-Heapify(A, i)
33

Complexity of Build-Heap

34

Proof of Linear Build Time

35

Heapsort Algorithm

36

Sorting: The Goal

37

Heapsort Strategy

38

Heapsort(A) — 1-indexed

Build-Max-Heap(A)
for i = A.length down to 2
  swap A[1] with A[i]
  heap_size = heap_size - 1
  Max-Heapify(A, 1)
39

Heapsort(A) — 0-indexed

Build-Max-Heap(A)
for i = A.length - 1 down to 1
  swap A[0] with A[i]
  heap_size = heap_size - 1
  Max-Heapify(A, 0)
40

Heapsort Analysis

41

Comparison

42

Priority Queues

43

Review: What is a Queue?

44

Motivation: Why Priority Queues?

45

Priority Queue: The Concept

46

Implementation Comparison

47

The Interface

48

Implementing with Heap

49

Insert: Float Up

50

Increase-Key Logic

51

Applications

52

Summary: Key Takeaways

53

What We Learned

54

Practice Problems

55

Problem 1

56

Problem 2

57

Problem 3

58

Problem 4: K-ary Heaps

59

Interactive: Binary Heap

60

Supplementary Resources