Heaps: my notes on up-heap, down-heap and building a heap
Personal notes, min-heap version, array-backed with the root at index 1.
- Parent of i: i / 2. Children of i: 2i and 2i + 1.
- Add: put the new item at the end, then up-heap. Swap with the parent while it's smaller than the parent.
- Remove: take the root, move the last item to the root, then down-heap. Swap with the SMALLER child while it's bigger than a child.
- Build heap: start at the last non-leaf (size / 2) and down-heap every index down to 1.
Things I got wrong at first: forgetting to compare with the smaller child, and off-by-one errors from mixing 0-based and 1-based indexing. Pick one convention and write it at the top of your code.
Comments
0-based vs 1-based messed me up for an entire evening, lol.
The smaller-child mistake got me too. Great notes.