Reading a Binary Heap by Hand

A binary min-heap keeps each parent no greater than its children. This places a minimum at the root and permits disorder between siblings.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Check the local rule
  2. Trace an insertion
  3. Restore the min-heap rule along one path
  4. Verify the parent rule on every occupied index

Check the local rule

The level-order array 2, 5, 3, 9 can be a min-heap. The children 5 and 3 each exceed the root. The child 9 exceeds parent 5. With zero-based indices, index \(i\) has children \(2i+1\) and \(2i+2\) when present.

Trace an insertion

Appending 1 gives it parent 5. Swap with 5 and then with 2. The root becomes 1. These local repairs implement a priority queue without sorting all entries.[1]

Restore the min-heap rule along one path

In the array [2, 5, 7, 9, 8], each parent is no larger than its children. Appending three puts it below seven. Exchanging their positions restores that edge, and three is still no smaller than the root two. The array layout is not a sequential sort. See priority queue behavior.

Before insertion: [2,5,7,9,8]
Append 3 at index 5, parent at 2 holds 7
Swap: [2,5,3,9,8,7]
Parent at 0 holds 2, so stop

Verify the parent rule on every occupied index

For zero-based array positions, the parent of \(i>0\) is \(\lfloor(i-1)/2\rfloor\). A test checking only the root misses broken interior edges that can affect later removals. Insert a small item, an equal item and a large item.

References

  1. Jeff Erickson, Algorithms ↩