Max Heap (Implementation)
Let's implement a max Heap.
We'll cover the following...
Max-heap Implementation #
Let’s start with some function declarations for the heap class.
Structure of our MaxHeap #
Declaring the private elements #
Implementing the constructor and size() #
Implementing the getMax() function
This function returns the maximum value from the heap, which is the root, i.e., the first value in the list. It does not modify the heap itself. If the heap is empty, this function returns -1. The time complexity of this function is in constant time, which is what makes heaps so special!
Implementing the removeMax() function
This function removes the maximum value from the heap. It first checks if the length of the heap is 1. If true, it deletes the value at index 0. Then, it checks if the length of the heap is greater than 1 if it is, it swaps the maximum value with the last leaf node, deletes it, and restores the max heap property on the rest of the tree by calling the maxHeapify() function on it. The time complexity of this function is in because that is the maximum number of nodes that would have to be traversed or swapped.
Implementing the insert() function
This function appends the given value to the heap list and calls the percolateUp() function on it. This function will keep on swapping the values of nodes until the heap property is restored. The time complexity of this function is in because that is the maximum number of nodes that would have to be traversed or swapped.
Implementing the percolateUp() function
This function restores the heap property by swapping the value at a parent node if it is less than the value at a child node. After swapping, the function is called recursively on each parent node until the root is reached. The time complexity of this function is in because that is the maximum number of nodes that would have to be traversed and/or swapped.
Implementing the maxHeapify() function
The maxHeapify() function restores the heap property after a node is removed. It restores the heap property, starting from a given node down to the leaves. It swaps the values of the parent nodes with the values of their largest child nodes until the heap property is restored. The time complexity of this function is in because that is the maximum number of nodes that would have to be traversed or swapped.
Building a max-heap
Let’s build a max-heap now. Suppose we have elements in an array which represents our heap. For every node to be positioned in accordance with the max-heap property, we call the maxHeapify method at every index of that array, starting from the bottom of the heap (lines 83-88).
Let’s derive a tight bound for the complexity of building a heap.
Notice that we start from the bottom of the heap, i.e., i = size-1 (line 85). If the height of the heap is ...