Binary Heap
Last updated
Last updated
A complete binary tree can be uniquely represented by storing its level order traversal in an array.
We skip the index zero cell of the array for the convenience of implementation so the the root is the second item in the array.
Consider element of the array, the
its left child is located at index
its right child is located at index
its parent is located at index
The new element is appended to the end of the heap (as the last element of the array).
The heap property is repaired by comparing the added element with its parent and moving the added element up a level (swapping positions with the parent).
The comparison is repeated until the parent is larger than or equal to the percolating element.
The worst-case runtime of the algorithm is , since we need at most one swap on each level of a heap on the path from the inserted node to the root.
The minimum element can be found at the root, which is the first element of the array.
We remove the root and replace it with the last element of the heap and then restore the heap property by percolating down.
The worst-case runtime is O{log n).