Skip to content

Commit

Permalink
feat: PQ - dequeue
Browse files Browse the repository at this point in the history
  • Loading branch information
andy922200 committed Apr 22, 2024
1 parent b7f3cf3 commit 9ed419e
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion app-ch9-20.js
Expand Up @@ -33,11 +33,54 @@ class PriorityQueue {
parentIndex = Math.floor((newIndex - 1) / 2);
}
}

dequeue(){
if (this.values.length === 0) return null;
if (this.values.length === 1) {
const removedNode = this.values.pop();
return removedNode;
}

[this.values[0], this.values[this.values.length - 1]] = [this.values[this.values.length - 1], this.values[0]];

const removedNode = this.values.pop();
this.maxHeapify(0)

return removedNode;
}

maxHeapify(i) {
let largestIndex = undefined;
let left = i * 2 + 1;
let right = i * 2 + 2;
const length = this.values.length;

left <= length - 1 && this.values[left].priority > this.values[i].priority
? largestIndex = left
: largestIndex = i;

if (right <= length - 1 && this.values[right].priority > this.values[largestIndex].priority) {
largestIndex = right;
}

if (largestIndex !== i) {
[this.values[i], this.values[largestIndex]] = [this.values[largestIndex], this.values[i]];
this.maxHeapify(largestIndex);
}
}
}

const pq1 = new PriorityQueue();
pq1.enqueue('Eat breakfast', 5);
pq1.enqueue('Learn Java', 2);
pq1.enqueue('Learn JavaScript', 7);
pq1.enqueue('Buy Textbooks', 8);
pq1.enqueue('Watch Netflix', 12);
pq1.enqueue('Pay Bills', 15);

console.log(pq1)

console.log(pq1)
while(pq1.values.length >= 1){
const { value, priority } = pq1.dequeue();
console.log(value + ' - Priority: ' + priority);
}

0 comments on commit 9ed419e

Please sign in to comment.