Data Structures: Create a Priority Queue Class
This commit is contained in:
parent
1d1c0c9964
commit
db8369efaf
74
Data Structures/priorityQueueClass.js
Normal file
74
Data Structures/priorityQueueClass.js
Normal file
@ -0,0 +1,74 @@
|
||||
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/create-a-priority-queue-class
|
||||
|
||||
function PriorityQueue() {
|
||||
this.collection = [];
|
||||
this.printCollection = function () {
|
||||
console.log(
|
||||
this.collection.map(([elem, priority, order]) => [elem, priority])
|
||||
);
|
||||
};
|
||||
// Only change code below this line
|
||||
this.order = 0;
|
||||
this.size = function () {
|
||||
return this.collection.length;
|
||||
};
|
||||
this.isEmpty = function () {
|
||||
return !this.collection.length;
|
||||
};
|
||||
this.swap = function (a, b) {
|
||||
const tmp = this.collection[a];
|
||||
this.collection[a] = this.collection[b];
|
||||
this.collection[b] = tmp;
|
||||
};
|
||||
this.changePriority = function (a, b) {
|
||||
return (
|
||||
this.collection[a][1] > this.collection[b][1] ||
|
||||
(this.collection[a][1] == this.collection[b][1] &&
|
||||
this.collection[a][2] > this.collection[b][2])
|
||||
);
|
||||
};
|
||||
this.enqueue = function (elem) {
|
||||
elem.push(this.order++);
|
||||
this.collection.push(elem);
|
||||
let me = this.collection.length - 1;
|
||||
let parent = Math.trunc((me - 1) / 2);
|
||||
while (this.changePriority(parent, me)) {
|
||||
this.swap(parent, me);
|
||||
me = parent;
|
||||
parent = Math.trunc((me - 1) / 2);
|
||||
}
|
||||
};
|
||||
this.dequeue = function () {
|
||||
if (this.isEmpty()) return;
|
||||
this.swap(0, this.collection.length - 1);
|
||||
const elem = this.collection.pop()[0];
|
||||
let me = 0;
|
||||
let leftChild = me * 2 + 1;
|
||||
let rightChild = leftChild + 1;
|
||||
while (
|
||||
(leftChild < this.collection.length &&
|
||||
this.changePriority(me, leftChild)) ||
|
||||
(rightChild < this.collection.length &&
|
||||
this.changePriority(me, rightChild))
|
||||
) {
|
||||
if (
|
||||
rightChild < this.collection.length &&
|
||||
this.changePriority(leftChild, rightChild)
|
||||
) {
|
||||
this.swap(me, rightChild);
|
||||
me = rightChild;
|
||||
} else {
|
||||
this.swap(me, leftChild);
|
||||
me = leftChild;
|
||||
}
|
||||
leftChild = me * 2 + 1;
|
||||
rightChild = leftChild + 1;
|
||||
}
|
||||
return elem;
|
||||
};
|
||||
this.front = function () {
|
||||
if (this.isEmpty()) return;
|
||||
return this.collection[0][0];
|
||||
};
|
||||
// Only change code above this line
|
||||
}
|
Loading…
Reference in New Issue
Block a user