UNPKG

entropyx

Version:

A simple data mining library, written in TypeScript

55 lines 1.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MaxHeap = void 0; class MaxHeap { constructor() { this.heap = []; } size() { return this.heap.length; } insert(item) { this.heap.push(item); this.bubbleUp(this.heap.length - 1); } extractMax() { if (this.heap.length === 0) return undefined; this.swap(0, this.heap.length - 1); const max = this.heap.pop(); this.bubbleDown(0); return max; } bubbleUp(index) { while (index > 0) { const parent = Math.floor((index - 1) / 2); if (this.heap[index].deltaQ <= this.heap[parent].deltaQ) break; this.swap(index, parent); index = parent; } } bubbleDown(index) { const length = this.heap.length; while (true) { const left = 2 * index + 1; const right = 2 * index + 2; let largest = index; if (left < length && this.heap[left].deltaQ > this.heap[largest].deltaQ) { largest = left; } if (right < length && this.heap[right].deltaQ > this.heap[largest].deltaQ) { largest = right; } if (largest === index) break; this.swap(index, largest); index = largest; } } swap(i, j) { [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; } } exports.MaxHeap = MaxHeap; //# sourceMappingURL=max-heap.js.map