|
| 1 | +class MinHeap { |
| 2 | + constructor(collection) { |
| 3 | + this.heap = []; |
| 4 | + |
| 5 | + if (collection) { |
| 6 | + collection.forEach((element) => { |
| 7 | + this.add(element); |
| 8 | + }); |
| 9 | + } |
| 10 | + } |
| 11 | + |
| 12 | + add(element) { |
| 13 | + this.heap.push(element); |
| 14 | + // check for the parent element & swap if required |
| 15 | + // eslint-disable-next-line no-underscore-dangle |
| 16 | + this.__traverseUpAndSwap(this.heap.length - 1); |
| 17 | + } |
| 18 | + |
| 19 | + getMin() { |
| 20 | + return this.heap[0] || null; |
| 21 | + } |
| 22 | + |
| 23 | + remove() { |
| 24 | + const min = this.heap[0] || null; |
| 25 | + |
| 26 | + if (this.heap.length > 1) { |
| 27 | + this.heap[0] = this.heap[this.heap.length - 1]; |
| 28 | + this.heap.pop(); |
| 29 | + // eslint-disable-next-line no-underscore-dangle |
| 30 | + this.__heapify(0); |
| 31 | + } |
| 32 | + if (this.heap.length === 1) { |
| 33 | + this.heap.pop(); |
| 34 | + } |
| 35 | + return min; |
| 36 | + } |
| 37 | + |
| 38 | + destroy() { |
| 39 | + this.heap = []; |
| 40 | + } |
| 41 | + |
| 42 | + // eslint-disable-next-line consistent-return |
| 43 | + __traverseUpAndSwap(index) { |
| 44 | + if (index <= 0) return null; |
| 45 | + |
| 46 | + const parent = Math.floor(index / 2); |
| 47 | + |
| 48 | + if (this.heap[parent] > this.heap[index]) { |
| 49 | + const temp = this.heap[parent]; |
| 50 | + this.heap[parent] = this.heap[index]; |
| 51 | + this.heap[index] = temp; |
| 52 | + // eslint-disable-next-line no-underscore-dangle |
| 53 | + this.__traverseUpAndSwap(parent); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + __heapify(index) { |
| 58 | + const left = index * 2; |
| 59 | + const right = index * 2 + 1; |
| 60 | + |
| 61 | + let smallest = index; |
| 62 | + |
| 63 | + if (this.heap.length > left && this.heap[smallest] > this.heap[left]) { |
| 64 | + smallest = left; |
| 65 | + } |
| 66 | + if (this.heap.length > right && this.heap[smallest] > this.heap[right]) { |
| 67 | + smallest = right; |
| 68 | + } |
| 69 | + if (smallest !== index) { |
| 70 | + const tmp = this.heap[smallest]; |
| 71 | + this.heap[smallest] = this.heap[index]; |
| 72 | + this.heap[index] = tmp; |
| 73 | + // eslint-disable-next-line no-underscore-dangle |
| 74 | + this.__heapify(smallest); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +module.exports = MinHeap; |
0 commit comments