Always Serving the Most Urgent
Sometimes you need the most important item first, not the oldest. A priority queue serves elements by priority rather than arrival. The structure that implements it efficiently is the binary heap.
A binary heap is a complete binary tree (filled level by level, left to right) satisfying the heap property:
| Heap Type | Root Element | Parent-Child Rule |
|---|---|---|
| Max-Heap | Maximum | Parent Children |
| Min-Heap | Minimum | Parent Children |
The extreme element is always available in time at the top.
Operations and Layout
Insertion and removal maintain the heap property via sifting in time:
- Insert: Place at the next open leaf, then sift up (swap with parent while larger).
- Remove: Take root, move last leaf there, then sift down (swap with larger child).
Because the tree is complete, store it in a plain array: node has children at and .
Common pitfall: Expecting a heap to be fully sorted. It is only partially ordered—parents relate to children, but siblings and cousins are unordered. Heaps give fast access to the extreme element, powering Dijkstra's and heapsort.