Taking the top — fill in two holes
In the last step you watched a heap in tables. Now the same thing is written down as an algorithm — and you fill in two missing pieces.
Pseudocode
Two operations. The first — push: sift up — is already written in Go (see the panel); it is here so you can recognise it:
Push(item):
append item at the end of the array
i ← len(a) − 1
while i > 0:
p ← (i−1)/2
c.Hit()
if a[p] ≤ a[i]: stop // parent no larger — in order
swap a[p] and a[i]
i ← p
The second — taking the top: sift down — is yours:
Pop():
top ← a[0]
a[0] ← the last element; shorten the array
i ← 0
loop:
child ← 2i+1 // the left one
if there is no child: stop // i is a leaf
if 2i+2 exists and is smaller than child:
child ← 2i+2 // 1 comparison
c.Hit()
if a[child] ≥ a[i]: stop // the smaller child is no smaller — in order
swap a[i] and a[child]
i ← child
return top
The last element travels to the root — the only way not to leave a hole in the array — and sinks until both children are no smaller.
It is the last element of the array that moves to the root, not one of the root's children.
Promoting the smaller child looks more natural and is wrong: that leaves a
hole where the child was, which has to be filled, and so on down to the leaves.
You get the right ordering and a broken shape — the array grows empty slots, and
2i+1 stops pointing at a child.
A heap's shape is a complete tree with no gaps, and that is precisely why the index arithmetic works at all.
Your job
Create heap.go and heap_test.go (see the panel).
heap.go is complete and compiles, but Pop does not work. NewMinHeap,
Len, Peek and Push are already written; Pop has its loop and two holes,
marked HOLE 1 and HOLE 2:
- HOLE 1 — moving the last element to the root. One line, before the array is shortened on the line just below it.
- HOLE 2 — the right child. The loop already looks at the left one; what is missing: if the right one exists and is smaller, take it. Look at the top of the loop — the absence of a child is already checked, but only the left one.
Nothing else needs changing.
heap_test.go is the verdict — you do not write it, you pass it. For now it
checks push and pop only:
TestTraceReproducesTheLessonTable— the same seven pushes and seven pops as the last step. After each it requires the same comparisons, the same swaps and the same array. If your heap "works" but the array differs, this is where you hear about it.TestPopKeepsTheHeapAndComesOutAscending— 500 scattered ratings. After every pop: the heap property holds, the length fell by one, and what came out is exactly the next smallest.
Worth noting
PeekisO(1). No loop, no comparison —a[0]. It is already written in three lines; compare it with what you will have to write forTopKHeap.Pushcompares against the parent;Popagainst both children. SoPopdoes roughly twice the comparisons per level thatPushdoes.- Swaps are not comparisons.
c.Hit()fires only when two ratings are compared; swaps accumulate inSwaps. Step 7 rests on that distinction. NewMinHeaptakes a capacity hint and uses it (make([]Item, 0, capacity)). That is what makes the whole structure one allocation — the number step 7 sets against 20,020.
Run the test before you fill anything in
Run it as it stands first:
$ go test ./...
--- FAIL: TestTraceReproducesTheLessonTable (0.00s)
heap_test.go:94: pop: rating / cmps / swaps / array = 12 / 1 / 0 / [12 19 15 41 22 17], want 12 / 3 / 2 / [15 19 17 41 22 33]
--- FAIL: TestPopKeepsTheHeapAndComesOutAscending (0.00s)
heap_test.go:125: pop 4 returned 0, want 1 — not the next smallest
FAIL
That is not an error — it is the starting point. The first message: the pop returned 12, but 12 is still at the root and 33 has vanished — nothing moved to the root, and the array was shortened from the end. The second: the same minimum is handed out again and again until the equal ratings run out.
Fill in HOLE 1 and run again:
--- FAIL: TestTraceReproducesTheLessonTable (0.00s)
heap_test.go:94: pop: rating / cmps / swaps / array = 12 / 2 / 1 / [19 33 15 41 22 17], want 12 / 3 / 2 / [15 19 17 41 22 33]
--- FAIL: TestPopKeepsTheHeapAndComesOutAscending (0.00s)
heap_test.go:131: the heap property broke after a pop, with 499 items left
Now 33 is at the root and sinking — but only to the left: past 19, while 15
was never compared. The root became 19 and its right child 15 is smaller than
it — the heap property is broken. Fill in HOLE 2 — you should see ok.
When it does not pass
Each of these is a real mistake, tried.
index out of range [6] with length 6— either HOLE 1 was written afterh.a = h.a[:last](the array is already shorter,h.a[last]no longer exists), or HOLE 2 looks atchild+1without checking that it exists.cmps / swaps … = 12 / 2 / 2 …, want 12 / 3 / 2— you compared the two children but did not count it. Every comparison needs ac.Hit().the heap property broke after a pop— HOLE 2 is empty, or it picked the larger child (>instead of<; in the table that gives12 / 4 / 1).pop N returned …, not the next smallest— HOLE 1 is empty or lifted the wrong value. If you move a child to the root, a duplicate appears in the array and 33 disappears: you get[15 19 17 41 22 19], expected[15 19 17 41 22 33].