A heap is a complete binary tree stored in an array. In a max-heap every parent is at least as large as its children, so the highest priority item is always at index 0. Insert and remove each move one item up or down a single path, which takes O(log n) steps. Click any node to see how its index finds its parent and children.
vector<int> hT. Level by level, left to right. A dashed red edge means the heap property is broken there.The class page asks for the cost of each operation. Try it yourself first.
| Implementation | Add | Remove top | Peek |
|---|---|---|---|
| Unsorted array or list | O(1) | O(n) | O(n) |
| Sorted array (top at the end) | O(n) | O(1) | O(1) |
| Sorted linked list (top at the head) | O(n) | O(1) | O(1) |
| Heap | O(log n) | O(log n) | O(1) |