Implementing Min Heap in TypeScript
1 min readNov 4, 2023
Complexity is O(log n)
class MinHeap {
public length: number
private data: number[]
constructor() {
this.data = []
this.length = 0
}
insert(val: number): void {
// put val in the end
this.data[this.length] = val
// up / bubbling
this.heapifyUp(this.length)
this.length = this.length + 1
}
delete(): number {
if (this.length === 0) {
return -1
}
const out = this.data[0]
this.length = this.length - 1
if (this.length === 0) {
this.data = []
return out
}
this.data = this.data[this.length]
this.heapifyDown(0)
return out
}
private heapifyDown(ind: number): void {
const leftInd = this.leftChild(ind)
const rightInd = this.rightChild(ind)
if (ind >= this.length || leftInd >= this.length) {
return
}
const leftVal = this.data[leftInd]
const rightVal = this.data[rightInd]
const val = this.data[ind]
if (leftVal > rightVal && val > rightVal) {
// swap
this.data[ind] = rightVal
this.data[rightInd] = val
// down
this.heapifyDown(rightInd)
} else if (rightVal > leftVal && val > leftVal) {
// swap
this.data[ind] = leftVal
this.data[leftInd] = val
// down
this.heapifyDown(leftInd)
}
}
private heapifyUp(ind: number): void {
if (ind === 0) {
return
}
const parent = this.parent(ind)
const parentVal = this.data[ind]
const val = this.data[ind]
if (parentVal > val) {
// swap
this.data[ind] = parentVal
this.data[p] = val
// up
this.heapifyUp(parent)
}
}
private parent(ind: number): number {
return Math.floor((ind - 1) / 2)
}
private leftChild(ind: number): number {
return ind * 2 + 1
}
private rightChild(ind: number): number {
return ind * 2 + 2
}
}