高优先级的患者先于低优先级的患者就医, 同样优先级的患者按照先来先服务的顺序就医。
规定:优先码的值最小的元素优先级最高。
function Patient(name, code) { this.name = name; this.code = code; } function Queue() { //用队列模拟基数排序对应的Queue构造函数中的方法一个都不能少,否则会出错 this.dataStore = []; this.enqueue = enqueue; this.dequeue = dequeue; this.toString = toString; } function enqueue(element) {//向队尾添加一个元素 this.dataStore.push(element); } function dequeue() {//对dequeue()方法的重写 var priority = 0; var code1 = this.dataStore[0].code; for ( var i = 1; i < this.dataStore.length; ++i) { if (this.dataStore[i].code < code1) { code1 = this.dataStore[i].code; priority = i; } } return this.dataStore.splice(priority, 1); } function toString() {//对toString()方法的重写 var retStr = ""; for ( var i = 0; i < this.dataStore.length; ++i) { retStr += this.dataStore[i].name + " code: " + this.dataStore[i].code + " <br/>"; } return retStr; } var ed = new Queue(); var p = new Patient("Smith", 5); ed.enqueue(p); p = new Patient("Jones", 4); ed.enqueue(p); p = new Patient("Fehrenbach", 6); ed.enqueue(p); p = new Patient("Brown", 1); ed.enqueue(p); p = new Patient("Ingram", 1); ed.enqueue(p); document.write(ed.toString() + "<br />"); var seen = ed.dequeue(); document.write("Patient being treated: " + seen[0].name + "<br />"); document.write("Patients waiting to be seen: " + "<br />") document.write(ed.toString() + "<br />"); // 下一轮 var seen = ed.dequeue(); document.write("Patient being treated: " + seen[0].name + "<br />"); document.write("Patients waiting to be seen: " + "<br />") document.write(ed.toString() + "<br />"); var seen = ed.dequeue(); document.write("Patient being treated: " + seen[0].name + "<br />"); document.write("Patients waiting to be seen: " + "<br />") document.write(ed.toString()); /*上述程序运行结果: Smith code: 5 Jones code: 4 Fehrenbach code: 6 Brown code: 1 Ingram code: 1 Patient being treated: Brown Patients waiting to be seen: Smith code: 5 Jones code: 4 Fehrenbach code: 6 Ingram code: 1 Patient being treated: Ingram Patients waiting to be seen: Smith code: 5 Jones code: 4 Fehrenbach code: 6 Patient being treated: Jones Patients waiting to be seen: Smith code: 5 Fehrenbach code: 6 */