A binary heap is a complete binary tree that satisfies the heap property. Notably two heaps can contain the same data but with items in different positions, the heap property allows multiple valid arrangements. Additionally, heaps can store the same value in multiple positions at the same time.
Binary heaps implement the same operations as a queue which is why they are typically used in their implementation. Specifically binary heaps implement the following operations:
template <class T>
class MinHeap {
public:
Heap(int initialCapacity);
// Insert an element
void insert(const T& element);
// Remove and return from the root (minimum value)
T removeMin();
}
template <class T>
class MinHeap {
public:
Heap(int initialCapacity);
// Insert an element
void insert(const T& element);
// Remove and return from the root (maximum value)
T removeMax();
}
Binary heaps despite being a representation of a tree are usually implemented using a resizable array. Where for a given node at index
Given a node at index
When a new element is inserted into a binary heap, first the algorithm finds the first available leftmost leaf on the bottom level (preserving the completeness of the tree).
The partial ordering is fixed by comparing the new value to it's parent and recursively swapping them until the value is no longer greater than it's parent (this operation is called heapify up).
The worst case performance for a insertion operation is
When we remove the root (ie. in a removeMin or removeMax) operation we start by copying the root so we can return it, we then replace the root node with the right-most leaf node (and remove the that leaf node from it's current position).
The partial ordering is fixed by comparing the new root to it's children and recursively swapping it with the largest child until the value is no longer greater than either of it's children (this operation is called heapify down). Finally the copied original root data is returned to the caller.
Similarly to insertion removing the root node is also