Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lecture 32 - Binary heaps: a tree stored in a Vec

A binary tree above the array row that stores it

Announcements




Learning objectives

By the end of today, you should be able to:

  • Explain what a priority queue is, and name a problem that needs one
  • Trace push and pop on a binary heap, and say why each is O(log n)
  • Read a heap out of a Vec: find a node's parent and children by arithmetic (you don't need to memorize the formulas)
  • Use BinaryHeap, by deriving Ord on your own type so it knows what "biggest" means

Who's next?

From the pre-work: where in everyday life does the most urgent one go next, regardless of what order they arrived in?

The ER waiting room, again

In the generics lecture we talked about the piles we could sort, and one was a waiting room at the ER. We could sort by urgency, and then call the first one.

Except the room keeps changing:

  • A new patient walks in every few minutes
  • The doctor calls the next patient every few minutes

Should we keep the room sorted? Every arrival means finding their spot, which is fast, but then shifting everyone behind them down one seat: O(n).

But we don't need to keep the room sorted. We only need to be able to answer one question: who's next?

A line where the most urgent goes first is a priority queue.

A priority queue has three operations

OperationMeaning
push(x)Add something, with its priority
pop()Remove what has the highest priority
peek()Look at it without taking it out

Rust has one in the standard library: BinaryHeap<T>.

use std::collections::BinaryHeap;

fn main() {
    let mut heap = BinaryHeap::new();
    heap.push(5);
    heap.push(10);
    heap.push(3);
    heap.push(8);
    println!("{}", heap.pop().unwrap()); 
    println!("{}", heap.pop().unwrap());  
}

Biggest first, every time. BinaryHeap is a max-heap: the biggest value is on top.

What's inside?

Debug printing shows us what it's storing:

use std::collections::BinaryHeap;

fn main() {
    let mut heap = BinaryHeap::new();
    heap.push(10);
    heap.push(30);
    heap.push(20);
    heap.push(5);
    println!("{:?}", heap);        
    println!("{:?}", heap.peek());
}

The biggest is first, and the rest isn't sorted.

So it's keeping some order... less than full sorted order, but enough to make push and pop easy.

for x in &heap walks that same unsorted order. To get values in order, pop in a loop, or call heap.into_sorted_vec().

Two ways to do it with a Vec

Unsorted Vec. Push on the end. To pop the biggest, scan everything.

Sorted Vec, biggest at the end. Pop off the end. To push, find the right spot and shift everything after it.

pushpop the biggest
Unsorted VecO(1)O(n)
Sorted VecO(n)O(1)
Binary heapO(log n)O(log n)

Each Vec is free on one side and O(n) on the other. A binary heap is a Vec with a rule about where things go, and the rule gets both operations down to O(log n).

Important: two different "heaps"

Like "stack", the word "heap" means two completely different things.

Heap memory, from before the midterm:

  • The region of memory where String, Vec, and Box keep their data
  • Reached through pointers from the stack
  • A memory-management idea

Heap data structure, today:

  • A tree with a rule: every parent is at least as big as its children
  • Used to build priority queues
  • Nothing to do with where it lives in memory

Same word, two meanings, but context should make it clear. We'll do the same thing for "stack" on Wednesday.

More tree words

  • A graph is a set of nodes with edges joining some of them.
  • A tree is a graph with one node on top, the root, and every other node hanging off exactly one node above it.
         A         Root: the top node, no parent
        / \
       B   C       B and C are children of A. A is their parent
      /   / \
     D   E   F     Leaves: no children
  • Height: how many rows
  • Binary tree: at most two children per node
  • Complete binary tree: every row is full except maybe the last, and the last fills left to right

A binary heap is a complete binary tree with the heap property: every parent is >= both its children.

A max-heap

         42              Root is the largest
        /  \
      30    20           Every parent >= its children
     / \    / \
   10  25  15  8         Tree is complete
   /
  5

Let's check each property.

Note what is not an issue: 25 is below 20 in the tree and larger than it, but 25 isn't 20's child. And siblings can be in any order. Only parent-to-child matters.

Not a max-heap:

         20              30 > 20, and 30 is 20's child
        /  \
      30    25

Complete, or not

Complete: every row full except the last, which fills left to right.

       42                      42
      /  \                    /  \
    30    20                30    20
   / \    /                   \    /
  10 25  15                   25  15

  Complete                 Not complete: a gap on the left

Why insist on this? Because a complete tree has no gaps, so its rows can be laid end to end.

The array trick

Read the tree row by row, left to right, and write it down:

Tree:
         42
        /  \
      30    20
     / \    / \
   10  25  15  8

Vec:   [42, 30, 20, 10, 25, 15, 8]
Index:   0   1   2   3   4   5   6

Now every family relationship is arithmetic:

  • Parent of index i: (i - 1) / 2
  • Left child of i: 2 * i + 1
  • Right child of i: 2 * i + 2

Check: 30 is at index 1. Parent is (1 - 1) / 2 = 0, which is 42. Children are 3 and 4, which are 10 and 25.

Activity 32, Problem 1: read the Vec

See Problem 1 on Activity 32.

Answer.

  1. Indices 2 * 1 + 1 = 3 and 2 * 1 + 2 = 4: 25 and 30
  2. Index (4 - 1) / 2 = 1: 40
  3. Yes. 50 >= 40, 35. 40 >= 25, 30. 35 >= 30, 15
  4. 50 on top; 40 and 35 under it; 25 and 30 under 40; 30 and 15 under 35

Where it lives: one block

let mut heap = BinaryHeap::new();
heap.push(10);
heap.push(30);
heap.push(20);
heap.push(5);
Stack:                          Heap:
┌─────────────────────────┐     ┌────┬────┬────┬────┐
│ main()                  │     │ 30 │ 10 │ 20 │ 5  │
│ └ heap: BinaryHeap<i32> │     └────┴────┴────┴────┘
│    ├ ptr ───────────────┼───▶   0    1    2    3
│    ├ len: 4             │
│    └ cap: 4             │
└─────────────────────────┘

That's the Vec picture again! One handle on the stack, one block on the heap, and it doubles when it fills up. The tree is a way of reading the block. Nothing in memory has branches.

On Friday we'll build a tree the other way, with a Box for every node.

Push: 35 arrives. Now what?

Think/pair/share

The only open spot that keeps the tree complete is the end of the last row, so 35 goes there:

         42
        /  \
      30    20
     / \    / \
   10  25  15  8
   /
  35

[42, 30, 20, 10, 25, 15, 8, 35]

That broke the heap property: 35 is under 10. How would you fix it? What's the least work that gets us back to a heap?

Push: add, then bubble up

  1. Put the new value at the end of the Vec, which is the next open spot in the last row
  2. Compare it with its parent. If it's bigger, swap
  3. Repeat until the parent is bigger, or it's the root

Insert 35 into [42, 30, 20, 10, 25, 15, 8]:

Step 1: add to the end         Step 2: 35 > 10, swap
         42                             42
        /  \                           /  \
      30    20                       30    20
     / \    / \                     / \    / \
   10  25  15  8                  35  25  15  8
   /                              /
  35                            10

[42, 30, 20, 10, 25, 15, 8, 35]   [42, 30, 20, 35, 25, 15, 8, 10]

Push: keep going

Step 3: 35 > 30, swap          Step 4: 35 < 42, stop
         42                             42
        /  \                           /  \
      35    20                       35    20
     / \    / \                     / \    / \
   30  25  15  8                  30  25  15  8
   /                              /
  10                            10

[42, 35, 20, 30, 25, 15, 8, 10]   [42, 35, 20, 30, 25, 15, 8, 10]

Each swap moves the value up one row. A heap with n values has about log n rows, so that's at most log n swaps: O(log n).

Push, in code

The whole thing, on a plain Vec<i32>:

fn push(heap: &mut Vec<i32>, x: i32) {
    heap.push(x);                            // 1. add at the end
    let mut i = heap.len() - 1;
    while i > 0 {
        let parent = (i - 1) / 2;
        if heap[i] <= heap[parent] { break; } // 3. parent is bigger: stop
        heap.swap(i, parent);                // 2. bubble up
        i = parent;
    }
}

fn main() {
    let mut heap = vec![42, 30, 20, 10, 25, 15, 8];
    push(&mut heap, 35);
    println!("{:?}", heap);  
}

So BinaryHeap::push is really just a Vec with swap and (i - 1) / 2 operations, on any type T: Ord.

Pop: 42 is gone. Now what?

Finding the biggest is free: it's the root. Take it out, and there's a hole on top:

         ??
        /  \
      35    20
     / \    / \
   30  25  15  8
   /
  10

Two problems. The tree has a hole, and whatever fills it has to be bigger than everything below it. What would you do?

Pop: replace, then bubble down

  1. Take the root. That's the answer
  2. Move the last value into the root's spot, so the tree stays complete
  3. Compare it with its children. If a child is bigger, swap with the larger child
  4. Repeat until both children are smaller, or there are no children

Pop from [42, 35, 20, 30, 25, 15, 8, 10]:

Step 1: take 42, move 10 up    Step 2: 10 < 35 and 20, swap with 35
         10                             35
        /  \                           /  \
      35    20                       10    20
     / \    / \                     / \    / \
   30  25  15  8                  30  25  15  8

[10, 35, 20, 30, 25, 15, 8]       [35, 10, 20, 30, 25, 15, 8]

Pop: keep going

Step 3: 10 < 30 and 25, swap with 30     Step 4: 10 has no children, stop
         35                                       35
        /  \                                     /  \
      30    20                                 30    20
     / \    / \                               / \    / \
   10  25  15  8                            10  25  15  8

[35, 30, 20, 10, 25, 15, 8]                 [35, 30, 20, 10, 25, 15, 8]

Same bound: one row per swap, log n rows, O(log n).

What each one costs

OperationCostWhy
push(x)O(log n)Bubble up, one row per swap
pop()O(log n)Bubble down, one row per swap
peek()O(1)Read index 0
BinaryHeap::from(vec)O(n)Faster than n pushes. The appendix has why

The reason it's log n: a complete binary tree with a million values has 20 rows. A billion, 30 rows.

Compare the sorted Vec: push costs n shifts. Here it costs at most 20 swaps.

What can be a T?

To know who's on top, the heap has to compare two values. So the type has to promise it can be compared:

use std::collections::BinaryHeap;

#[derive(Debug, PartialEq, Eq)]
struct Striker { name: String, goals: u32 }

fn main() {
    let mut heap = BinaryHeap::new();
    heap.push(Striker { name: String::from("Messi"), goals: 20 });
    heap.push(Striker { name: String::from("Haaland"), goals: 27 });
    heap.push(Striker { name: String::from("Kane"), goals: 24 });
    for _ in 0..3 {
        let s = heap.pop().unwrap();
        println!("{} ({} goals)", s.name, s.goals);
    }
}
error[E0277]: the trait bound `Striker: Ord` is not satisfied
note: required by a bound in `BinaryHeap::<T, A>::push`

On Friday, HashSet asked for Eq + Hash. BinaryHeap asks for Ord.

The quick fix is to derive it, which takes all four comparison traits:

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Striker { name: String, goals: u32 }

That compiles, and it pops Messi first. Derived Ord compares field by field in declaration order, and name comes first. For top scorer first, we would have to write cmp ourselves.

Top K: the ten biggest of a billion

You have a billion rows and want the ten largest. Sorting all of them is O(n log n), and you'd throw away all but ten.

use std::collections::BinaryHeap;

fn top_k(nums: Vec<i32>, k: usize) -> Vec<i32> {
    let mut heap = BinaryHeap::from(nums);   // O(n)
    let mut result = Vec::new();
    for _ in 0..k {                           // k times
        if let Some(max) = heap.pop() {       // O(log n) each
            result.push(max);
        }
    }
    result
}

fn main() {
    let scores = vec![31, 7, 44, 12, 58, 23, 44, 9];
    println!("{:?}", top_k(scores, 3));      // [58, 44, 44]
}

Cost: O(n + k log n). For small k that's O(n), one pass over the data.

Another one, the running median of a stream of numbers, works with two heaps leaning on each other. It's in the appendix if you're curious.

Key takeaways

  • A priority queue pops by priority
  • A binary heap is a complete binary tree where every parent >= its children
  • It's stored in a Vec: parent at (i - 1) / 2, children at 2i + 1 and 2i + 2
  • push and pop are O(log n), peek is O(1)
  • BinaryHeap<T> needs T: Ord, and cmp decides what's on top
NeedUse
Pop by priorityBinaryHeap
Pop the oldest firstVecDeque, on Wednesday
Pop the newest firstVec

Activity 32

See Activity 32. Problem 1 is done, so start at Problem 2.

Appendix: smallest first, with Reverse

BinaryHeap always pops the biggest. For smallest-first, wrap each value in Reverse, which flips every comparison:

use std::collections::BinaryHeap;
use std::cmp::Reverse;

fn main() {
    let mut heap = BinaryHeap::new();
    heap.push(Reverse(10));
    heap.push(Reverse(30));
    heap.push(Reverse(20));
    heap.push(Reverse(5));
    println!("{:?}", heap.peek());          // Some(Reverse(5))
}

Reverse(5) is "bigger" than Reverse(10), so 5 is on top.

The ER room would actually use this: the lowest triage number is the most urgent. The running median below needs it too.

Appendix: building a heap in O(n)

BinaryHeap::from(vec) doesn't push n times. It starts from the unsorted Vec, treats it as a complete tree that happens to break the heap property, and bubbles down from the last parent back to the root.

Most nodes are near the bottom and have almost nowhere to go. Half the nodes are leaves and cost nothing. A quarter are one row up and cost at most one swap. And so on:

Total work = n/2 * 0 + n/4 * 1 + n/8 * 2 + n/16 * 3 + ...
           = n * (1/4 + 2/8 + 3/16 + 4/32 + ...)
           = n * 1
           = O(n)

Pushing n times instead costs O(n log n), because each push can travel the full height.

Appendix: heapsort

Pop a max-heap until it's empty and the values come out in descending order. That's a sorting algorithm:

use std::collections::BinaryHeap;

fn heapsort(nums: Vec<i32>) -> Vec<i32> {
    let mut heap = BinaryHeap::from(nums);   // O(n)
    let mut sorted = Vec::new();
    while let Some(max) = heap.pop() {       // n pops, O(log n) each
        sorted.push(max);
    }
    sorted.reverse();                         // descending to ascending, O(n)
    sorted
}

fn main() {
    println!("{:?}", heapsort(vec![3, 1, 4, 1, 5, 9, 2, 6]));   // [1, 1, 2, 3, 4, 5, 6, 9]
}

O(n) + O(n log n) + O(n) = O(n log n), the same as the sorts we've met. heap.into_sorted_vec() does the same thing.

Appendix: the running median

Numbers arrive one at a time and after each one you want the median so far. Keep two heaps: a max-heap holding the smaller half, and a min-heap holding the larger half. The median is on top of one of them, or halfway between the two tops.

use std::collections::BinaryHeap;
use std::cmp::Reverse;

fn main() {
    let mut lower = BinaryHeap::new();   // max-heap: the smaller half, biggest on top
    let mut upper = BinaryHeap::new();   // min-heap: the larger half, smallest on top

    for x in [5, 15, 1, 3, 8, 7, 9, 10] {
        // 1. Put it in the half it belongs to
        match lower.peek() {
            Some(&top) if x > top => upper.push(Reverse(x)),
            _ => lower.push(x),
        }

        // 2. Rebalance: lower has the same count as upper, or one more
        if lower.len() > upper.len() + 1 {
            let top = lower.pop().unwrap();
            upper.push(Reverse(top));
        } else if upper.len() > lower.len() {
            let Reverse(top) = upper.pop().unwrap();
            lower.push(top);
        }

        // 3. The median is on top of lower, or between the two tops
        let median = if lower.len() > upper.len() {
            *lower.peek().unwrap() as f64
        } else {
            let Reverse(hi) = *upper.peek().unwrap();
            (*lower.peek().unwrap() + hi) as f64 / 2.0
        };
        println!("after {:>2}: median {}", x, median);
    }
}

Each arrival is a push and maybe a pop, so O(log n) per number. Sorting after every arrival would be O(n log n) per number.