簡體   English   中英

優先隊列javascript

[英]Priority queue javascript

在下面的優先級隊列中,當將具有相同優先級的元素加入隊列時,它們彼此相鄰添加,但我看不到任何特定條件。

    function PriorityQueue() {
    var collection = [];
    this.printCollection = function() {
      (console.log(collection));
    };
    this.enqueue = function(element){
        if (this.isEmpty()){ 
            collection.push(element);
        } else {
            var added = false;
            for (var i=0; i<collection.length; i++){
                 if (element[1] < collection[i][1]){ //checking priorities
                    collection.splice(i,0,element);
                    added = true;
                    break;
                }
            }
            if (!added){
                collection.push(element);
            }
        }
    };
    this.dequeue = function() {
        var value = collection.shift();
        return value[0];
       };
    this.front = function() {
        return collection[0];
    };
    this.size = function() {
        return collection.length; 
    };
    this.isEmpty = function() {
        return (collection.length === 0); 
    };
}

var pq = new PriorityQueue(); 
pq.enqueue(['Beau Carnes', 2]); 
pq.enqueue(['Quincy Larson', 3]);
pq.enqueue(['Ewa Mitulska-Wójcik', 1])
pq.enqueue(['Briana Swift', 2])
pq.printCollection();
pq.dequeue();
console.log(pq.front());
pq.printCollection();

具有較高優先級的元素被添加到最后,但具有相同優先級的元素被添加到彼此相鄰的...

條件在拼接調用中

collection.splice(i,0,element);

解釋入隊功能

 this.enqueue = function(element){
        //check if collection is empty push the element
        if (this.isEmpty()){ 
            collection.push(element);
        } else {
            //Set a flag to check if element added 
            //(this is to determine is the for loop found a match)
            var added = false;
            for (var i=0; i<collection.length; i++){
                 //if the element at the index 'i' in the collection has
                 //higher priority you need the splice the array at that 
                 //index and insert the element there
                 if (element[1] < collection[i][1]){ //checking priorities
                    //splice the array at that index and insert the element
                    collection.splice(i,0,element);
                    //satisfy the added condition
                    added = true;
                    //break the for loop
                    break;
                }
            }
            //if not added in the loop
            if (!added){
                //push to the end on the collection
                collection.push(element);
            }
        }
    };

您可以使用下面提到的庫。 只需執行 npm install collectiondatalib 即可。

特點: https : //www.npmjs.com/package/collectiondatalib

易於使用,所有集合和搜索排序方法都可用。

您也可以在該頁面上找到源代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM