- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 285字
- 2025-02-25 19:09:24
Priority Queue
A priority queue is operationally similar the simple queues, that is, they support the same API, but there is a small addition to the data that they hold. Along with the element (your data), they can also persist a priority, which is just a numerical value indicating the priority of your element in the queue.
Addition or removal of these elements from the queue is based on priority. You can either have a minimum priority queue or a maximum priority queue, to help establish whether you are adding elements based on increasing priority or decreasing priority. We will take a look at how the add() method can substitute the add() method of the simple queue that we defined earlier:
add(newEl) {
let queue = items.get(pqkey);
let newElPosition = queue.length;
if(!queue.length) {
queue.push(newEl);
return;
}
for (let [i,v] of queue.entries()) {
if(newEl.priority > v.priority) {
newElPosition = i;
break;
}
}
queue.splice(newElPosition, 0, newEl);
}
Since we are accounting for the priority of the elements while they are being inserted into the stack, we do not have to concern ourselves with priority while we remove elements from the queue, so the remove() method is the same for both simple and priority queues. Other utility methods, such as front(), clear(), peek(), and size(), have no correlation with the type of data that is being saved in the queue, so they remain unchanged as well.