我们已经了解过了队列,接下来了解一下什么是优先级队列:
其实程序就是对生活的一种描述,之前我们了解过队列,一个队列就好比生活中我们去火车站进站,每个人都需要排队,依次进站乘车。
但是我们考虑到这个一个现象:
在火车站进站时,都会规定军人优先,这里就涉及到了优先级的概念。在程序中亦是如此,队列也有优先级队列之说。
接下来实现一下优先级队列的封装:
function PriorityQueue() {
// 内部类
function QueueElement(element, priority) {
this.element = element;
this.priority = priority;
}
// 封装属性
this.item = [];
// 1. enqueue
PriorityQueue.prototype.enqueue = function(element, priority) {
// 拿到需要插入的元素对象
let queueElement = new QueueElement(element, priority);
// 如果队列中本来没有元素,则直接插入
if (this.item.length == 0) {
this.item.push(queueElement);
} else {
// 定义一个变量用于存储是否插入成功
var added = false;
// 这里规定优先级值小的在前面
// 如果队列中本来有元素,则依次比较优先级,当遇到优先级值大于它的优先级值的元素,则插入到该元素之前
for (let i = 0; i < this.item.length; i ++) {
if (queueElement.priority < this.item[i].priority) {
this.item.splice(i, 0, queueElement);
added = true;
break;
}
}
// 最后剩下没有比它优先级值大的元素
if (!added) {
this.item.push(queueElement);
}
}
}
// 2. dequeue
PriorityQueue.prototype.dequeue = function() {
return this.item.shift();
}
// 3. front
PriorityQueue.prototype.front = function() {
return this.item[0];
}
// 4. isEmpty
PriorityQueue.prototype.isEmpty = function() {
return this.item.length == 0;
}
// 5. size
PriorityQueue.prototype.size = function() {
return this.item.length;
}
// 6. toString
PriorityQueue.prototype.toString = function() {
let resultString = '';
for (let i = 0; i < this.item.length; i ++) {
resultString += this.item[i].element + ' ';
}
resultString = resultString.trim();
return resultString;
}
}
当我们测试的时候可以输入一下代码:
let pq = new PriorityQueue();
pq.enqueue('a', 100);
pq.enqueue('b', 200);
pq.enqueue('d', 400);
pq.enqueue('c', 300);
pq.enqueue('e', 500);
alert(pq);
可以看到弹出框中已经帮我们按照优先级排好顺序了。