JS優先隊列排序。出隊時,先找出優先級最高的元素,再按照先進先出出隊。


JS優先隊列排序。出隊時,先找出優先級最高的元素,再按照先進先出出隊。

 

/*
* 優先隊列
* 出隊時,先找出優先級最高的元素,再按照先進先出出隊。
* */
function Queue(){
    this.dataStore = [];//存放隊列的數組,初始化為空
    this.enqueue = enqueue;//向隊列尾部添加一個元素
    this.dequeue = dequeue;//出隊時,先找出優先級最高的元素,再按照先進先出出隊。
    this.theFront = theFront;//讀取隊首的元素
    this.back = back;//對取隊尾的元素
    this.toStrings = toStrings;//顯示隊列內的所有元素
    this.empty = empty;//判斷隊列是否為空
}
/*先定義存儲隊列元素的對象*/
function Patient(name,code){
    this.name = name;//code是一個整數,表示患者的優先級
    this.code = code;
}

function enqueue(element){
    this.dataStore.push(element);
}

function dequeue(){
    var minindex = 0;
    var priority = this.dataStore[0].code;
    for(var i = 1;i<this.dataStore.length;i++){
        if(this.dataStore[i].code < priority){
            priority = this.dataStore[i].code;
            minindex = i;
        }
    }
    return this.dataStore.splice(minindex,1);
}

function theFront(){
    return this.dataStore[0];
}

function back(){
    return this.dataStore[this.dataStore.length-1];
}

function toStrings(){
    return this.dataStore;
}

function empty(){
    if(this.dataStore.length == 0){
       return true;
    }else{
        return false;
    }
}

/*優先隊列的實現*/
var ed = new Queue();
var p = new Patient("aa",5);
ed.enqueue(p);
var p = new Patient("bb",4);
ed.enqueue(p);
var p = new Patient("cc",3);
ed.enqueue(p);
var p = new Patient("dd",3);
ed.enqueue(p);
var p = new Patient("ee",1);
ed.enqueue(p);
console.log(ed.toStrings());
console.log(ed.dequeue());//[ Patient { name: 'ee', code: 1 } ]
console.log(ed.dequeue());//[ Patient { name: 'cc', code: 3 } ]
console.log(ed.dequeue());//[ Patient { name: 'dd', code: 3 } ]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM