class MaxHeap {
heap: number[] = [];
constructor(arr: number[]) {
this.heap = arr;
this.buildMaxHeap();
}
buildMaxHeap() {
for (let i = Math.floor(this.heap.length / 2) - 1; i >= 0; i--) {
this.heapify(i);
}
}
heapify(i: number) {
const n = this.heap.length;
let largest = i;
const left = 2 * i + 1;
const right = 2 * i + 2;
if (left < n && this.heap[left] > this.heap[largest]) {
largest = left;
}
if (right < n && 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(): number | null {
if (this.heap.length === 0) return null;
const max = this.heap[0];
this.heap[0] = this.heap[this.heap.length - 1];
this.heap.pop();
this.heapify(0);
return max;
}
}
function findKthLargest(arr: number[], k: number): number | null {
const maxHeap = new MaxHeap(arr);
let kthLargest: number | null = null;
for (let i = 0; i < k; i++) {
kthLargest = maxHeap.extractMax();
}
return kthLargest;
}
// Driver code
const arr = [3, 10, 5, 7, 9, 8, 4];
const k = 3;
const result = findKthLargest(arr, k);
console.log(`${k}th largest element is ${result}`);for (let i = Math.floor(this.heap.length / 2) - 1; i >= 0; i--) { this.heapify(i); }
build max heap by heapifying from bottom non-leaf nodes up
if (left < n && this.heap[left] > this.heap[largest]) { largest = left; }
find largest among node and left child
if (right < n && this.heap[right] > this.heap[largest]) { largest = right; }
find largest among current largest and right child
if (largest !== i) { swap and heapify(largest); }
swap and continue heapify to maintain max heap property
const max = this.heap[0]; this.heap[0] = this.heap.pop(); this.heapify(0); return max;
extract max root, replace with last element, then heapify root
for (let i = 0; i < k; i++) { kthLargest = maxHeap.extractMax(); }
extract max k times to get kth largest