优先级队列javascript

时间:2018-02-20 10:20:45

标签: javascript data-structures

在以下优先级队列中,当排队具有相同优先级的元素时,它们会相互相邻添加,但我无法看到任何特定条件。

    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();

具有较高优先级的元素会添加到结尾,但具有相同优先级的元素会相互相邻添加...

2 个答案:

答案 0 :(得分:0)

条件是在拼接调用中

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);
            }
        }
    };

答案 1 :(得分:-1)

您可以使用下面提到的库。只需npm安装collectiondatalib。

功能:https://www.npmjs.com/package/collectiondatalib

易于使用,并且提供了所有馆藏和搜索排序方法。

您也可以在该页面上找到源代码。

相关问题