Last active
March 10, 2020 16:24
-
-
Save Prottoy2938/5bf843aedf613c1ea38f352a62bd5752 to your computer and use it in GitHub Desktop.
Priority Queue made in Min Binary Heap.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(value, priority) { | |
this.value = value; | |
this.priority = priority; | |
} | |
} | |
class PriorityQueue { | |
constructor() { | |
this.values = []; | |
} | |
enqueue(val, priority) { | |
let newNode = new Node(val, priority); | |
this.values.push(newNode); | |
this.bubbleUp(); | |
} | |
bubbleUp() { | |
let idx = this.values.length - 1; | |
const element = this.values[idx]; | |
while (idx > 0) { | |
let parentIdx = Math.floor((idx - 1) / 2); | |
let parent = this.values[parentIdx]; | |
if (element.priority >= parent.priority) break; | |
this.values[parentIdx] = element; | |
this.values[idx] = parent; | |
idx = parentIdx; | |
} | |
} | |
dequeue() { | |
const min = this.values[0]; | |
const end = this.values.pop(); | |
if (this.values.length > 0) { | |
this.values[0] = end; | |
this.sinkDown(); | |
} | |
return min; | |
} | |
sinkDown() { | |
let idx = 0; | |
const length = this.values.length; | |
const element = this.values[0]; | |
while (true) { | |
let leftChildIdx = 2 * idx + 1; | |
let rightChildIdx = 2 * idx + 2; | |
let leftChild, rightChild; | |
let swap = null; | |
if (leftChildIdx < length) { | |
leftChild = this.values[leftChildIdx]; | |
if (leftChild.priority < element.priority) { | |
swap = leftChildIdx; | |
} | |
} | |
if (rightChildIdx < length) { | |
rightChild = this.values[rightChildIdx]; | |
if ( | |
(swap === null && rightChild.priority < element.priority) || | |
(swap !== null && rightChild.priority < leftChild.priority) | |
) { | |
swap = rightChildIdx; | |
} | |
} | |
if (swap === null) break; | |
this.values[idx] = this.values[swap]; | |
this.values[swap] = element; | |
idx = swap; | |
} | |
} | |
} | |
//EXAMPLES ================================================================================================= | |
const priorityQueue = new PriorityQueue(); | |
priorityQueue.enqueue("Contribute on GitHub", 9); | |
priorityQueue.enqueue("Take Rest", 2); | |
priorityQueue.enqueue("Finish Chaper 24 on JavaScript course", 1); | |
priorityQueue.enqueue("Learn Nodejs", 3); | |
priorityQueue.enqueue("Learn Nodejs", 1); | |
priorityQueue.enqueue("Learn Nodejs", 12); | |
priorityQueue.enqueue("Learn Nodejs", 123); | |
priorityQueue.enqueue("Learn Nodejs", 0); | |
priorityQueue.dequeue(); | |
priorityQueue.dequeue(); | |
priorityQueue.dequeue(); | |
//I am exhausted right now, I didn't created any comments and made any optimization. Thanks to Colt Steele for helping me create this. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment