使用 JavaScript 向優先順序佇列新增元素


為優先順序佇列加入元素是指按元素的優先順序順序將它們新增到陣列中。我們將認為較高數字是較高的優先順序。我們將遍歷容器,直到找到較低優先順序,然後在那裡新增元素。如果沒有,那麼我們將其推送到容器的末尾。

請注意,我們正在使用資料和優先順序建立元素物件。因此,我們可以將入列函式實現如下 -  

示例

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 } ]

正如您所見,元素是有序的。入列函式的工作原理類似於插入排序的插入。

更新日期: 2020 年 6 月 15 日

156 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.