1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| class Heap { constructor(arr = [], sortBy = 0) { this.Heap = []; this.sortBy = sortBy; for (let i = 0; i < arr.length; i++) { this.Heap[i + 1] = arr[i]; } for (let i = Math.floor(this.Heap.length / 2); i >= 1; i--) { this.shiftDown(i); } }
shiftDown(index) { while (2 * index < this.Heap.length) { let i = 2 * index; if (i + 1 < this.Heap.length && this.compare(i + 1, i)) { i += 1; } if (this.compare(index, i)) { break; } this.swap(index, i); index = i; } }
shiftUp(index) { while (index > 1 && this.compare(index, Math.floor(index / 2))) { this.swap(Math.floor(index / 2), index); index = Math.floor(index / 2); } }
compare(i, j) { return this.sortBy === 0 ? this.Heap[i] > this.Heap[j] : this.Heap[i] < this.Heap[j]; }
insert(num) { this.Heap.push(num); this.shiftUp(this.getLenth()); }
pop() { let item; item = this.Heap[1]; this.swap(1, this.getLenth()); this.Heap.pop(); this.shiftDown(1); return item; }
getLenth() { return this.Heap.length - 1; }
swap(i, j) { if (i !== j) { const temp = this.Heap[i]; this.Heap[i] = this.Heap[j]; this.Heap[j] = temp; } } }
const maxHeap = new Heap([1, 2, 34, 52, 123, 4551]); maxHeap.insert(2222); console.log(maxHeap.pop(), maxHeap.pop());
const minHeap = new Heap([1, 2, 34, 52, 123, 4551], 1); console.log(minHeap); minHeap.insert(2222); console.log(minHeap);
console.log(minHeap.pop(), minHeap.pop());
|