{ values: number[] }
1function insert(val):2 heap.push(val)3 i = heap.length - 14 while i > 0 and heap[parent(i)] > heap[i]:5 swap(heap[parent(i)], heap[i])6 i = parent(i)78function extractMin():9 min = heap[0]10 heap[0] = heap.pop()11 i = 012 while true:13 smallest = min(i, left(i), right(i))14 if smallest == i: break15 swap(heap[i], heap[smallest])16 i = smallest17 return min
1class MinHeap {2 private heap: number[] = [];34 insert(val: number) {5 this.heap.push(val);6 let i = this.heap.length - 1;7 while (i > 0) {8 const p = Math.floor((i - 1) / 2);9 if (this.heap[p] <= this.heap[i]) break;10 [this.heap[p], this.heap[i]] = [this.heap[i], this.heap[p]];11 i = p;12 }13 }1415 extractMin(): number {16 const min = this.heap[0];17 this.heap[0] = this.heap.pop()!;18 let i = 0;19 while (true) {20 let s = i;21 const l = 2*i+1, r = 2*i+2;22 if (l < this.heap.length && this.heap[l] < this.heap[s]) s = l;23 if (r < this.heap.length && this.heap[r] < this.heap[s]) s = r;24 if (s === i) break;25 [this.heap[i], this.heap[s]] = [this.heap[s], this.heap[i]];26 i = s;27 }28 return min;29 }30}