class MinHeap {
constructor() {
this.heap = []
}
insert(val) {
this.heap.push(val) // add at end
this.bubbleUp() // reorder up
}
bubbleUp() {
let idx = this.heap.length - 1
while (idx > 0) {
let parentIdx = Math.floor((idx - 1) / 2)
if (this.heap[parentIdx] <= this.heap[idx]) break
;[this.heap[parentIdx], this.heap[idx]] = [this.heap[idx], this.heap[parentIdx]] // swap
idx = parentIdx // move up
}
}
extractMin() {
if (this.heap.length === 0) return null
if (this.heap.length === 1) return this.heap.pop()
const min = this.heap[0]
this.heap[0] = this.heap.pop() // move last to root
this.bubbleDown() // reorder down
return min
}
bubbleDown() {
let idx = 0
const length = this.heap.length
while (true) {
let leftIdx = 2 * idx + 1
let rightIdx = 2 * idx + 2
let swapIdx = null
if (leftIdx < length && this.heap[leftIdx] < this.heap[idx]) {
swapIdx = leftIdx
}
if (rightIdx < length && this.heap[rightIdx] < (swapIdx === null ? this.heap[idx] : this.heap[leftIdx])) {
swapIdx = rightIdx
}
if (swapIdx === null) break
;[this.heap[idx], this.heap[swapIdx]] = [this.heap[swapIdx], this.heap[idx]]
idx = swapIdx
}
}
print() {
return this.heap.join(' -> ')
}
}
// Driver code to show difference
// Sorted array operations
let sortedArr = [1, 3, 5, 7, 9]
// Remove smallest (shift)
sortedArr.shift()
// Insert 2 and keep sorted
sortedArr.push(2)
sortedArr.sort((a, b) => a - b)
// Heap operations
const heap = new MinHeap()
[1, 3, 5, 7, 9].forEach(v => heap.insert(v))
heap.extractMin() // remove smallest
heap.insert(2) // add 2
console.log('Sorted Array final:', sortedArr.join(' -> '))
console.log('Heap final:', heap.print())this.heap.push(val) // add at end
insert new element at bottom of heap
while (idx > 0) { ... swap ... idx = parentIdx }
bubble up new element to restore heap order
const min = this.heap[0]
this.heap[0] = this.heap.pop()
remove root and replace with last element
while (true) { ... swapIdx ... swap ... idx = swapIdx }
bubble down root element to restore heap order
remove smallest from sorted array by shifting all elements
sortedArr.push(2)
sortedArr.sort((a, b) => a - b)
insert new element and re-sort array
Sorted Array final: 2 -> 3 -> 5 -> 7 -> 9
Heap final: 2 -> 3 -> 5 -> 9 -> 7