Codele / Data structures
Heaps and priority queues
In a hospital waiting room the most urgent patient is seen first, not the first to arrive. A heap keeps the most urgent one on top, and it is quick to update.
- A priority queue serves the most urgent item first, not the first to arrive, like a hospital waiting room.
- A heap is a tree where every parent is more urgent (smaller) than its children. So the top is always the most urgent.
- A heap fits in a plain list: place 0 is the top, and the parent of place i is at place (i - 1) // 2.
- To add, put the new item at the bottom, then bubble up: swap with its parent while it is more urgent.
- Bubbling up only visits one item per level, so adding stays quick even in a big waiting room.
Loading the playable lesson…