Complete binary tree
Every level is full except possibly the last, which is filled from left to right. This allows compact array storage.
A binary heap is a complete binary tree stored compactly in an array. In a max heap, every parent is greater than or equal to its children. In a min heap, every parent is less than or equal to its children.
Example max heap loaded. Choose an operation.
parent(i) = floor((i - 1) / 2) leftChild(i) = 2i + 1 rightChild(i) = 2i + 2 insert: append, then sift up extract: replace root, then sift down
Every level is full except possibly the last, which is filled from left to right. This allows compact array storage.
After insertion, swap the new value with its parent while the heap property is violated.
After extraction, move the last value to the root and repeatedly swap it with the more appropriate child.
A heap guarantees parent–child order only. The array is not sorted, but the root always has the highest or lowest priority.
| Operation | Time | Reason |
|---|---|---|
| Peek root | O(1) | The root is at index 0. |
| Insert | O(log n) | Sift-up follows one path. |
| Extract root | O(log n) | Sift-down follows one path. |
| Build heap | O(n) | Bottom-up construction has linear aggregate cost. |
| Heap Sort | O(n log n) | The root is extracted n times. |