![]() |
VOOZH | about |
A binary heap is a complete binary tree that satisfies the heap property. The heap property states that for a max-heap, every parent node has a value greater than or equal to its children, and for a min-heap, every parent node has a value less than or equal to its children. Binary heaps are commonly used to implement priority queues because they provide an efficient way to access and modify the minimum or maximum element.
In this article, we will learn how to implement a binary heap in C++, including its basic operations along with their time and space complexity analysis.
A binary heap is a binary tree with the following properties:
A binary heap is typically implemented using an array. This is because the complete binary tree property allows us to use a simple array representation where the parent and child relationships are easily calculated using array indices.
The root element will be at Arr[0]. For any element at index i:
The following diagram demonstrates how a binary max heap is represented using an array in C++:
The following diagram demonstrates how a binary min heap is represented using an array in C++:
To represent a Binary Heap in C++, we will implement a class BinaryHeap and use a to store the elements of the heap. We'll implement a class to keep the binary heap generic so that it can store multiple data types.
template <typename T>
class BinaryHeap {
private:
vector<T> heap;
bool isMinHeap;
int currentSize;
int maxCapacity;
here:
Following are the basic operations that are required to work with a binary heap in C++:
| Operation | Description | Time Complexity | Space Complexity |
|---|---|---|---|
| isEmpty | Checks if the heap is empty | O(1) | O(1) |
| insert | Inserts a new element into the heap | O(log n) | O(1) |
| extractMin | Removes and returns the minimum element (min-heap) | O(log n) | O(1) |
| getMin | Returns the minimum element without removing it | O(1) | O(1) |
| heapify | Ensures the heap property is maintained. | O(log n) | O(1) |
- Initialize the smallest node as the current node, i.
- Calculate the left child index as 2i+12i + 12i+1.
- Calculate the right child index as 2i+22i + 22i+2.
- If the left child exists (i.e., it is within the array bounds) and is less than the current smallest node, update the smallest node to the left child.
- If the right child exists (i.e., it is within the array bounds) and is less than the current smallest node, update the smallest node to the right child.
- If the smallest node is not the current node, i, swap the current node with the smallest node using the std::swap function.
- Recursively apply the heapify operation to the subtree rooted at the smallest node.
- Append the new key to the end of the array.
- Initialize the index i as the index of the newly inserted key (last element of the array).
- Call the heapifyUp
- While the key at index i is less than its parent and i is not the root:
- Swap the key with its parent.
- Update i to the parent index.
- Continue this process until the heap property is restored.
- Check if the heap is empty. If true, throw an underflow_error.
- If the heap has only one element, remove and return that element.
- Store the minimum value (root of the heap) in a temporary variable.
- Replace the root of the heap with the last element in the array.
- Remove the last element from the array.
- Apply the heapify operation on the root to restore the heap property.
- Return the stored minimum value.
- The deleteKey function is implemented with the function signature: void Heap::deleteKey(int i).
- Check if the index i is valid (within the array bounds). If not, throw an out_of_range exception.
- Replace the key at index i with the last element in the array.
- Remove the last element from the array.
- Apply the heapify operation on the subtree rooted at index i to restore the heap property.
- The decreaseKey function is implemented with the function signature: void Heap::decreaseKey(int i, int newValue).
- Check if the index i is valid and the new value is less than the current value. If not, throw an invalid_argument exception.
- Update the value at index i to the new value.
- While the key at index i is less than its parent and i is not the root:
- Swap the key with its parent.
- Update i to the parent index.
- Continue this process until the heap property is restored.
- The printHeap function is implemented with the function signature: void Heap::printHeap() const.
- Iterate through each element in the array.
- Print each element followed by a space.
- Print a newline at the end.
The following program demonstrates how we can implement a Binary Heap in C++:
Min Heap: 2 3 15 5 4 45 Minimum element: 2 After extracting min: 3 4 15 5 45 After deleting 4: 3 5 15 45 After decreasing key at index 2 to 1: 1 5 3 45
Following are some of the common applications of Binary Heap: