Skip to content

Instantly share code, notes, and snippets.

@samteb
Created June 22, 2019 20:04
Show Gist options
  • Save samteb/8055b12a50cddbbc99ee3f0736210af0 to your computer and use it in GitHub Desktop.
Save samteb/8055b12a50cddbbc99ee3f0736210af0 to your computer and use it in GitHub Desktop.
class Node {
constructor (value, priority) {
this.value = value;
this.priority = priority;
}
}
class PriorityQueue {
constructor () {
this.values = [];
}
enqueue (value, priority) {
const node = new Node(value, priority);
this.values.push(node);
this.bubbleUp();
}
bubbleUp () {
let idx = this.values.length - 1;
const element = this.values[idx];
while (idx > 0) {
const parentIdx = Math.floor((idx - 1) / 2);
const parent = this.values[parentIdx];
if (parent.priority <= element.priority) break;
this.values[parentIdx] = element;
this.values[idx] = parent;
idx = parentIdx;
}
}
dequeue () {
const max = this.values[0];
const end = this.values.pop();
if (this.values.length > 0){
this.values[0] = end;
this.sinkDown();
}
return max;
}
sinkDown () {
let idx = 0;
const element = this.values[idx];
const length = this.values.length;
while (true) {
const leftChildIdx = 2 * idx + 1;
const rightChildIdx = 2 * idx + 2;
let leftChild = null;
let rightChild = null;
let swapIdx = null;
if (leftChildIdx < length) {
leftChild = this.values[leftChildIdx];
if (leftChild.priority < element.priority) {
swapIdx = leftChildIdx;
}
}
if (rightChildIdx < length) {
rightChild = this.values[rightChildIdx];
if (
(swapIdx === null && rightChild.priority < element.priority) ||
(swapIdx !== null && rightChild.priority < leftChild.priority)
) {
swapIdx = rightChildIdx;
}
}
if (swapIdx === null) break;
this.values[idx] = this.values[swapIdx];
this.values[swapIdx] = element;
idx = swapIdx;
}
}
}
const priorityQueue = new PriorityQueue();
priorityQueue.enqueue('common cold',5);
priorityQueue.enqueue('gunshot wound', 1);
priorityQueue.enqueue('high fever',4);
priorityQueue.enqueue('broken arm',2);
priorityQueue.enqueue('glass in foot',3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment