Implementing the Binary Heap
The priority queue chapter worked with the binary heap by hand. In this chapter, you will implement it twice: first from linked nodes, then in an array.
After reading this chapter, you should be able to:
- Find the path from the root to any position in a complete tree by writing the position’s number in binary, in
- Implement
addandremoveon a linked heap, with a recursiveaddthat uses the call stack in place of parent references to swim the new value up - Trace a recursive
addon a linked heap as a call stack - Store a binary heap in an array in level order, and move between a node and its parent or children by index arithmetic
- Implement an array heap, with
swimandsinkas loops - Explain why the array is the usual way to store a binary heap, comparing the two heaps by cost and memory
You can download the accompanying code for this chapter: starter and solution.
Sections
- A Heap Built from Nodes
- Finding the Next Open Slot
- The Path in Binary
- Reaching the Parent
- add, Recursively
- remove in Code
- Tracing a Recursive add
- A Heap in an Array
- Tracing the Array
- The ArrayHeap Class and Its Helpers
- swim and sink in an Array
- Implementing peek, add, and remove
- Two Heaps, Side by Side