UNPKG

pq-heaps-ts

Version:

implementation of priority queues using heaps

54 lines (53 loc) 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MaxHeap = void 0; // implement max heap for generic type class MaxHeap { constructor() { this.heap = []; this.push = (num) => { this.heap.push(num); this.heapifyUp(this.heap.length - 1); }; this.pop = () => { const max = this.heap[0]; this.heap[0] = this.heap[this.heap.length - 1]; this.heap.pop(); this.heapifyDown(0); return max; }; this.top = () => this.heap[0]; this.heapifyUp = (index) => { if (index === 0) return; const parentIndex = Math.floor((index - 1) / 2); if (this.heap[index] > this.heap[parentIndex]) { [this.heap[index], this.heap[parentIndex]] = [ this.heap[parentIndex], this.heap[index], ]; this.heapifyUp(parentIndex); } }; this.heapifyDown = (index) => { const leftChildIndex = index * 2 + 1; const rightChildIndex = index * 2 + 2; const leftChild = this.heap[leftChildIndex]; const rightChild = this.heap[rightChildIndex]; const largestChildIndex = leftChildIndex < this.heap.length && leftChild > rightChild ? leftChildIndex : rightChildIndex; if (this.heap[index] < this.heap[largestChildIndex]) { [this.heap[index], this.heap[largestChildIndex]] = [ this.heap[largestChildIndex], this.heap[index], ]; this.heapifyDown(largestChildIndex); } }; this.size = () => this.heap.length; this.isEmpty = () => this.heap.length === 0; this.print = () => console.log(this.heap); } } exports.MaxHeap = MaxHeap;