Max Heap (Implementation)
Let's implement a max heap!
Max Heap: Skeleton Code
Let’s start with some function declarations for the heap class.
The __percolateUp() function is meant to restore the heap property going up from a node to the root.
The __maxHeapify() function restores the heap property starting from a given node down to the leaves.
The two underscores before the __percolateUp() and __maxHeapify() functions imply that these functions should be treated as private functions.
class maxHeap {constructor() {}insert(val) {}getMax() {}removeMax() {}__percolateUp(index) {}__maxHeapify(index) {}}var heap = new maxHeap()
Implementing the constructor
The constructor will initialize an array that will contain the values of the heap. It will also store the number of elements currently present in the heap.
class maxHeap {constructor() {this.heap=[];this.elements = 0;}insert(val) {}getMax() {}removeMax() {}__percolateUp(index) {}__maxHeapify(index) {}}var heap = new maxHeap()
Implementing the insert() function
This function appends the given value to the heap array and calls the __percolateUp() function on it. This function will swap the values at parent-child nodes until the heap property is restored. The time complexity of this function is in ...