A Min Heap always keeps the smallest element at the root, making it ideal for quickly accessing the smallest value in a changing dataset.
A Max Heap keeps the largest element at the root, so it is best when you want quick access to the largest value, such as in heap sort or priority queues prioritizing highest values.
class MinHeap { heap: number[] = []; insert(val: number) { this.heap.push(val); this.bubbleUp(); } bubbleUp() { let index = this.heap.length - 1; while (index > 0) { let parentIndex = Math.floor((index - 1) / 2); if (this.heap[parentIndex] <= this.heap[index]) break; [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]]; index = parentIndex; } } printHeap() { return this.heap.join(' -> ') + ' -> null'; } } const minHeap = new MinHeap(); [10, 4, 15, 20, 0].forEach(num => minHeap.insert(num)); console.log(minHeap.printHeap());
After inserting 10, 4, 15, 20, and 0, the Min Heap reorganizes to keep the smallest element at the root and maintain heap property. The final array representation is [0, 4, 15, 20, 10].
class MaxHeap { heap: number[] = []; insert(val: number) { this.heap.push(val); this.bubbleUp(); } bubbleUp() { let index = this.heap.length - 1; while (index > 0) { let parentIndex = Math.floor((index - 1) / 2); if (this.heap[parentIndex] >= this.heap[index]) break; [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]]; index = parentIndex; } } printHeap() { return this.heap.join(' -> ') + ' -> null'; } } const maxHeap = new MaxHeap(); [3, 8, 5, 12, 7].forEach(num => maxHeap.insert(num)); console.log(maxHeap.printHeap());
After inserting the numbers, the Max Heap array is [12, 8, 5, 3, 7], which prints as '12 -> 8 -> 5 -> 3 -> 7 -> null'.
To maintain median efficiently, use a Max Heap for the smaller half (to get the largest of smaller numbers) and a Min Heap for the larger half (to get the smallest of larger numbers). This allows quick median calculation.