官术网_书友最值得收藏!

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.

A smart move while creating a priority queue would be to optimize your code and decide whether you would like to determine the priority at the time of addition or removal. That way, you are not overcalculating or analyzing your dataset at each step.
主站蜘蛛池模板: 政和县| 即墨市| 曲阜市| 巫溪县| 丰城市| 高雄市| 兴仁县| 无棣县| 清苑县| 柳州市| 临颍县| 台安县| 云浮市| 额济纳旗| 富源县| 吴旗县| 左权县| 曲沃县| 怀化市| 贵南县| 河北区| 丽水市| 襄樊市| 永寿县| 岑巩县| 墨玉县| 泰来县| 太仓市| 临汾市| 巧家县| 平舆县| 清新县| 绍兴市| 黑龙江省| 万安县| 漳州市| 抚宁县| 宁津县| 二手房| 姚安县| 陆河县|