4. Identify the bug in the following code that tries to find the 3rd largest element using a max heap:
class MaxHeap {
constructor(arr) {
this.heap = arr;
this.buildHeap();
}
buildHeap() {
for (let i = 0; i < this.heap.length / 2; i++) {
this.heapify(i);
}
}
heapify(i) {
let largest = i;
let left = 2 * i + 1;
let right = 2 * i + 2;
if (left < this.heap.length && this.heap[left] > this.heap[largest]) largest = left;
if (right < this.heap.length && this.heap[right] > this.heap[largest]) largest = right;
if (largest !== i) {
[this.heap[i], this.heap[largest]] = [this.heap[largest], this.heap[i]];
this.heapify(largest);
}
}
extractMax() {
if (this.heap.length === 0) return null;
const max = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapify(0);
return max;
}
}
const arr = [7, 10, 4, 3, 20, 15];
const maxHeap = new MaxHeap(arr);
let kthLargest;
for (let i = 0; i < 3; i++) {
kthLargest = maxHeap.extractMax();
}
console.log(kthLargest);