微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!
最高专题提供最高的最新资讯内容,帮你更好的了解最高。
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 } ]