Binary Heap Simulator
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.
Peek rootO(1)
InsertO(log n)
Extract rootO(log n)
Build heapO(n)
Heap operations
Array representation
Example max heap loaded. Choose an operation.
Heap size0
Height0
Comparisons0
Swaps0
Current operation path
—
Heap Sort result
—
Array index relationships
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
Heap concepts
Complete binary tree
Every level is full except possibly the last, which is filled from left to right. This makes compact array storage possible.
Sift up
After insertion, compare the new value with its parent and swap while the heap property is violated.
Sift down
After extraction, move the last value to the root and repeatedly swap it with the better child.
Not globally sorted
A heap guarantees parent-child order only. The root always has the highest or lowest priority, but the whole array is not sorted.
Complexity summary
| Operation | Time | Reason |
|---|---|---|
| Peek root | O(1) | The root is stored at index 0. |
| Insert | O(log n) | Sift-up follows one root-to-leaf path. |
| Extract root | O(log n) | Sift-down follows one path. |
| Build heap | O(n) | Bottom-up heap construction has linear aggregate cost. |
| Heap Sort | O(n log n) | The root is extracted repeatedly. |