使用 JavaScript 向 PriorityQueue 新增元素
將元素入列到 PriorityQueue 意味著按照元素的優先順序順序將元素新增到陣列中。我們認為較高的數字具有較高的優先順序。我們將迴圈遍歷容器,直到找到較低的優先順序,然後將元素新增到那裡。如果沒有,我們將把它放在容器的末尾。
請注意,我們用資料和優先順序建立元素物件。因此,我們可以按如下方式實現 enqueue 函式 -
示例
enqueue(data, priority) {
// Check if Queue is full
if (this.isFull()) {
console.log("Queue Overflow!");
return;
}
let currElem = new this.Element(data, priority);
let addedFlag = false;
// Since we want to add elements to end, we'll just push them.
for(let i = 0; i < this.container.length; i ++) {
if(currElem.priority < this.container[i].priority) {
this.container.splice(i, 0, currElem);
addedFlag = true; break;
}
}
if (!addedFlag) {
this.container.push(currElem);
}
}您可以使用 - 檢查此函式是否正常工作
示例
let q = new PriorityQueue(4);
q.enqueue("Hello", 3);
q.enqueue("World", 2);
q.enqueue("Foo", 8);
q.display();輸出
這將給出輸出 -
[ { data: 'World', priority: 2 },
{ data: 'Hello', priority: 3 },
{ data: 'Foo', priority: 8 } ]如您所見,元素按排序順序排列。enqueue 函式的工作原理類似於插入排序的插入。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP