Heaps and Priority Queues · seed 1 · A4, ink-friendly. The answer key prints on its own page for grown-ups.

Heaps that always hand you the smallest first

Computing · Algorithms & Data Structures · ages 19-20
Name ______________________   Date ____________
  1. In a heap array the root is at index 0. Where are the children of index 1?

    • 2 and 3
    • 3 and 4
    • 1 and 2
  2. A priority queue holds several tasks. Which task comes out first?

    • The most important one
    • The one added last
    • The one that arrived first
  3. In a min heap, every parent is no larger than its children, so the smallest item sits at the root.

    Circle one:   True   False

  4. The root is removed from a heap with several items left. What is the repair?

    • Move the last item to the root and sift down
    • Shift every item one slot left
    • Append a copy of the root
  5. A new item lands in a heap and breaks the value rule with its parent. What do you do?

    • Move it straight to the root
    • Swap it with the smaller child
    • Swap it with its parent and keep sifting up
  6. In a heap array with the root at index 0, a node sits at index 2. What index holds its left child?

    Answer: ______________

  7. A teammate keeps a sorted list and calls removal instant but inserts painful. What do you suggest?

    • Store items unsorted and scan every time
    • Keep the list, since inserts are already cheap
    • Switch to a heap so both insert and extract cost log n
  8. Why do heap insert and extract each cost log n?

    • They scan the whole array
    • Each fix walks a single root to leaf path
    • They sort the array after every step
LightMySky · lightmysky.comW1-mt_W-ofiMiXWs-s1

Answer key

For grown-ups. Fold this page away before handing over the rest.

Heaps that always hand you the smallest first W1-mt_W-ofiMiXWs-s1

  1. 3 and 4 · Children of i sit at 2i+1 and 2i+2, so 3 and 4.
  2. The most important one · Priority order beats arrival order in this structure.
  3. True · That value rule is what keeps the minimum ready at the top.
  4. Move the last item to the root and sift down · Extract moves the last item up top, then sifts down past the smaller child.
  5. Swap it with its parent and keep sifting up · Insert fixes upward: swap with the parent until the rule holds.
  6. 5 · The left child of i is at 2i+1, and 2 times 2 plus 1 is 5.
  7. Switch to a heap so both insert and extract cost log n · A sorted list shifts on every insert, while a heap keeps both steps at log n.
  8. Each fix walks a single root to leaf path · One path down a full tree is log n long, and the fix follows exactly one.
Worksheet · LightMySky