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

Activity 32: Heaps on paper

Name:

Problem 1: read the Vec (in lecture)

A BinaryHeap<i32> prints as:

[50, 40, 35, 25, 30, 30, 15]

Parent of i is (i - 1) / 2. Children of i are 2i + 1 and 2i + 2.

  1. What are the children of the element at index 1 (the 40)?
  2. What is the parent of the element at index 4 (the 30)?
  3. Is this a valid max-heap? Which pairs did you check?
  4. Draw the tree.






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

Problem 2: which of these are max-heaps?

Tree A:          Tree B:          Tree C:
    90               70               80
   /  \             /  \             /  \
  75  60           65  72           70  60
 / \  /           /  \            /      \
40 55 58         30  40          50      55
  1. Which trees are valid max-heaps?
  2. For each one that isn't, say what's wrong: the heap property, or the shape?
  3. Write Tree A as a Vec.



Answer.

  1. Tree A only
  2. Tree B breaks the heap property: 72 is a child of 70. Tree C has the right values in the right order but isn't complete: the last row has a gap under 60, so the rows can't be laid end to end in a Vec
  3. [90, 75, 60, 40, 55, 58]

Problem 3: trace a push and a pop

Start from this max-heap. After every swap, draw the tree and write the Vec under it.

       60
      /  \
    45    50
   / \    /
  20 30  40

[60, 45, 50, 20, 30, 40]

a. Push 55. How many comparisons did it take, and how many swaps?













Answer. 55 goes in at index 6, the right child of 50. 55 > 50, swap. 55 < 60, stop.

       60
      /  \
    45    55
   / \    / \
  20 30  40  50

[60, 45, 55, 20, 30, 40, 50]

b. Now pop. What comes out? Draw the heap after every swap.













Answer. 60 comes out. The last value, 50, moves to the root. Its children are 45 and 55, and 55 is the larger, so swap with 55. Now 50's only child is 40, which is smaller, so stop.

       55
      /  \
    45    50
   / \    /
  20 30  40

[55, 45, 50, 20, 30, 40]

Swapping with 45 instead would have put 55 under 45, which breaks the heap property.

Problem 4: read one, write one

a. What does this print? Each print! goes on the same line.

use std::collections::BinaryHeap;

fn main() {
    let mut heap = BinaryHeap::new();
    for cost in [12, 4, 9, 4, 20] {
        heap.push(cost);
    }
    println!("{:?}", heap.peek());     // line A

    heap.pop();
    heap.push(25);
    for _ in 0..5 {
        print!("{} ", heap.pop().unwrap());   // line B
    }
}

Line A: ________________________     Line B: ________________________

Answer. Line A prints Some(20). peek returns an Option, since the heap might be empty, and the biggest is on top.

Line B prints 25 12 9 4 4. The pop took out the 20, the push added a 25, and the loop drains biggest-first. Duplicates are fine in a heap.

b. Write best_two, which takes a Vec<i32> of scores and returns the two highest as a tuple, highest first. Use BinaryHeap::from and pop. unwrap is fine here, since the test has plenty of scores.

use std::collections::BinaryHeap;

fn best_two(scores: Vec<i32>) -> (i32, i32) {




}

fn main() {
    println!("{:?}", best_two(vec![31, 7, 44, 12, 58]));   // (58, 44)
}

What's the Big-O of best_two, for n scores? How does that compare to sorting the Vec and reading the last two?


Answer.

fn best_two(scores: Vec<i32>) -> (i32, i32) {
    let mut heap = BinaryHeap::from(scores);
    let first = heap.pop().unwrap();
    let second = heap.pop().unwrap();
    (first, second)
}

BinaryHeap::from is O(n), and each pop is O(log n), so O(n + 2 log n) = O(n). Sorting first is O(n log n), and it orders every score when we only wanted two.

Problem 5: which structure?

For each one, pick Vec, sorted Vec, HashSet, or BinaryHeap, and say in a few words why.

  1. A game server has thousands of scheduled events, each with a time. Every tick, run whichever is soonest. New events get scheduled constantly.
  2. Dealing cards: before handing one out, check whether it's already been dealt this hand.
  3. The moves of a chess game, in the order they were played, for replay.
  4. A leaderboard printed once, in full, top to bottom, when the tournament is over.




Answer.

  1. BinaryHeap, set up so the soonest time counts as biggest (the appendix on Reverse shows how). Pushes and pops keep coming, and each one is O(log n). A sorted Vec would cost O(n) per new event
  2. HashSet. The question is "is this in here?", and that's O(1)
  3. Vec. Order of arrival, read back in order. Nothing to search for
  4. Sort a Vec once, O(n log n).