Skip to content

Instantly share code, notes, and snippets.

@or9
Created February 24, 2021 13:39
Show Gist options
  • Save or9/41d14aafd9d0b0bca3a5efc4c1baeec6 to your computer and use it in GitHub Desktop.
Save or9/41d14aafd9d0b0bca3a5efc4c1baeec6 to your computer and use it in GitHub Desktop.
Example heap implementation from Mike Peritz for comparison purposes via https://codeburst.io/implementing-a-complete-binary-heap-in-javascript-the-priority-queue-7d85bd256ecf
class PriorityQueue {
constructor() {
this.heap = [null]
}
insert(value, priority) {
const newNode = new PriorityQueueNode(value, priority);
this.heap.push(newNode);
let currentNodeIdx = this.heap.length - 1;
let currentNodeParentIdx = Math.floor(currentNodeIdx / 2);
while (this.heap[currentNodeParentIdx] && newNode.priority > this.heap[currentNodeParentIdx].priority) {
const parent = this.heap[currentNodeParentIdx];
this.heap[currentNodeParentIdx] = newNode;
this.heap[currentNodeIdx] = parent;
currentNodeIdx = currentNodeParentIdx;
currentNodeParentIdx = Math.floor(currentNodeIdx / 2);
}
}
remove() {
if (this.heap.length < 3) {
const toReturn = this.heap.pop();
this.heap[0] = null;
return toReturn;
}
const toRemove = this.heap[1];
this.heap[1] = this.heap.pop();
let currentIdx = 1;
let [left, right] = [2*currentIdx, 2*currentIdx + 1];
let currentChildIdx = this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left;
while (this.heap[currentChildIdx] && this.heap[currentIdx].priority <= this.heap[currentChildIdx].priority) {
let currentNode = this.heap[currentIdx]
let currentChildNode = this.heap[currentChildIdx];
this.heap[currentChildIdx] = currentNode;
this.heap[currentIdx] = currentChildNode;
}
return toRemove;
}
}
class PriorityQueueNode {
constructor(val, priority) {
this.value = val;
this.priority = priority;
this.next = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment