Short answer: A binary heap stores a complete binary tree in an array. The parent of index i is floor((i−1)/2), and the children are 2i+1 and 2i+2, for zero-based indexes. The heap property says every parent is ordered before its children. Sift up repairs an insertion at the end. Sift down repairs a hole. Building a heap from an array by sifting down from the last parent is Θ(n). Each later insert or extract is O(log n).
What the problem actually asks
A priority queue needs the minimum, or the maximum, and it needs to insert a key, faster than a sorted array and with better locality than a pointer tree. The complete binary tree fills indices with no gaps, so the children of i are arithmetic rather than pointers. The only invariant a sift has to restore is the parent-child order along one path.
The linear build is the fact most often missed. Inserting n keys one by one is O(n log n). Sifting down from the middle of the array is linear because most subtrees are short.
What the algorithm guarantees
Insert and decrease-key, implemented as sift up, are O(log n). Extract-min and delete, implemented as moving the last leaf into the hole and sifting down, are O(log n). Heapify is Θ(n). Extra memory is the array itself. A binary heap does not find an arbitrary key quickly, and it does not keep a stable order among equal keys unless an explicit counter is added to the comparison.
Decrease-key needs the index of the element inside the array. A heap of bare values, with no handle map, cannot decrease a key that the caller only knows by identity. Dijkstra’s algorithm needs those handles, or it must push duplicate entries and ignore stale ones.
The working steps
- Store the heap in a dynamic array. The minimum sits at index 0 in a min-heap.
- To insert, append the key and sift up: while the key is smaller than its parent, swap them.
- To extract the minimum, read index 0, move the last element into index 0, shrink the array, and sift down. Sift down swaps with the smaller child until the parent is smaller than both children or a leaf is reached.
- To heapify an array, sift down from index floor(n/2)−1 through 0.
- To decrease a key, write the new value at its index and sift up. The caller must have the index.
The logarithmic bound is one sift along a root path. It is not a sorted array, and a search for a non-extremal key is linear. A Fibonacci heap improves the amortized cost of decrease-key to constant time and is rarely faster in practice. A binary heap is the default priority queue.
Approaches that look simpler and fail
| Approach | Why it fails when the array indexes are one-based in a zero-based language |
|---|---|
| Use children 2i and 2i+1 on a zero-based array | Index 0 then points at itself as a child. Zero-based children are 2i+1 and 2i+2. |
| Build the heap by n insertions and quote a linear build | n insertions cost O(n log n). The linear bound is the bottom-up sift from the last parent. |
| Sift up during that bottom-up build | Sift up walks toward the root from every node and loses the linear bound. Construction moves the hole downward. |
| Decrease a key without its index | The value may sit anywhere. Finding it is a scan. Dijkstra needs a handle or a duplicate-entry convention. |
A worst-case in-place sort built from this heap is heapsort. A decrease-key with an amortized constant bound is the Fibonacci heap. A balanced search tree sorts keys and also finds arbitrary ones, which a heap does not.
A working example
This Python fragment sifts a binary heap stored in an array and extracts the minimums. Children of i are 2i+1 and 2i+2. It prints 1 2 3 4.
def heapify(a, n, i):
while True:
left, right, best = 2 * i + 1, 2 * i + 2, i
if left < n and a[left] < a[best]:
best = left
if right < n and a[right] < a[best]:
best = right
if best == i:
return
a[i], a[best] = a[best], a[i]
i = best
def build(a):
for i in range(len(a) // 2 - 1, -1, -1):
heapify(a, len(a), i)
def extract(a):
last = a.pop()
if not a:
return last
root, a[0] = a[0], last
heapify(a, len(a), 0)
return root
h = [4, 1, 3, 2]
build(h)
print(*(extract(h) for _ in range(4)))
Where it is used
The binary heap is the priority queue in Python’s heapq, Java’s PriorityQueue, and C++ priority_queue. Dijkstra and event simulations pull the next earliest item from that array. A red-black tree can order the same keys, at the cost of pointers the heap does not store.
When you can drop this algorithm
Drop a binary heap when the access pattern is a full sort of a static array. Heapsort or a library sort is the direct tool. Keep the heap for a priority queue, for Dijkstra, and for a linear heapify when only the parent-child order is required.
Why this stays published
We publish this so a search for a binary heap returns the zero-based child indexes and the linear bottom-up heapify. A binary heap implements a priority queue in an array with O(log n) sifts, and it builds from an unsorted array in linear time by sifting down from the last parent.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
