Overview
A binary heap is a tree-shaped data structure, usually stored in an array, that keeps elements arranged so the highest-priority item is always at the root.| Operations | Complexity | Description |
|---|---|---|
| Peek | O(1) | The top element is always at the root. |
| Insert | O(log n) | The tree needs to be adjusted to keep the heap structure. |
| Remove Top | O(log n) | The tree needs to be adjusted to keep the heap structure. |
Structure
Binary heaps are complete binary trees, meaning they stay compact by filling levels from left to right.Min-heap
Every parent is smaller than or equal to its children, so the minimum value is at the top.[10, 15, 20, 30, 45, 50, 25, 75, 100]

Max-heap
Every parent is greater than or equal to its children, so the maximum value is at the top.[100, 75, 50, 30, 45, 20, 25, 15, 10]

Relationships
In an array-based heap, parent and child positions are found using simple index formulas.Example heap:
[100, 75, 50, 30, 45, 20, 25, 15, 10]45 (at index 4) is Math.floor((4 - 1) / 2) = Math.floor(1.5) = 1, which is 75.
Left child index:
1 * 2 + 1 = 3, which is 30.
Right child index:
1 * 2 + 2 = 4, which is 45.
Implementation
Binary Heap (PriorityQueue)
The initial compare function decides what “higher priority” means, so it determines whether the heap behaves like a
min-heap or a max-heap.Insert
The insert method appends the new value to the end of the array, then percolates up from that last index.Percolating up
Percolating up
Repeatedly compare the current value with its parent. If the current value has higher priority according to
compare (meaning compare(child, parent) < 0), swap them.Remove
The remove method first handles small cases. If the heap is empty, it returnsundefined. If it has one item, it pops and returns it.
Otherwise, it stores the top value (at index 0), replaces the root with the last element (using pop()), then percolates down from the root.
Percolating down
Percolating down
Repeatedly compare the current node with its children. Choose the child with higher priority according to
compare (the one that should be closer to the top), and swap if that child should come before the current node. When done, return the stored top value.Heapify (Optional)
Turn a random array into a Binary Heap. It copies the array into the internal heap, then works bottom-up from the last parent to the root. At each parent index, it percolates down to fix that subtree. Once it reaches index 0, the whole array satisfies the heap structure.Inserting items one by one takes
O(n log n), but heapify builds the heap in O(n).