<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
//封装优先级队列
function PriorityQueue(){
//在PriorityQueue重新创建一个类:可以理解成内部类
function QueueElement(element,priority){
this.element = element;
this.priority = priority;
}
//封装属性
this.items = [];
//实现插入
PriorityQueue.prototype.enqueue = function(element,priority){
//1.创建 QueueElement对象
var queueElement = new QueueElement(element,priority);
//2.判断队列是否为空
if(this.items.length == 0){
this.items.push(queueElement);
}else{
var added = false;
for(var i = 0; i < this.items.length;i++){
if(queueElement.priority < this.items[i].priority){
this.items.splice(i,0,queueElement); //插入函数
added = true;
break;
}
}
if(!added){
this.items.push(queueElement);
}
}
}
//方法
//2.从队列中删除元素
PriorityQueue.prototype.dequeue = function(){
return this.items.shift();
}
//3.查看队列元素
PriorityQueue.prototype.front = function(){
return this.items[0];
}
//4.判断队列是否为空
PriorityQueue.prototype.isEmpty = function(){
return this.items.length == 0;
}
//5.查看队列中元素个数
PriorityQueue.prototype.size = function(){
return this.items.length;
}
//6.toString方法
PriorityQueue.prototype.toString = function(){
var resultString = '';
for(var i = 0;i < this.items.length;i++){
resultString += this.items[i].element + '.' + this.items[i].priority + ' ';
}
return resultString;
}
}
//测试代码
var priorityqueue = new PriorityQueue();
priorityqueue.enqueue('abc',100);
priorityqueue.enqueue('def',80);
priorityqueue.enqueue('ghi',60);
priorityqueue.enqueue('jkl',40);
priorityqueue.enqueue('mno',20);
alert(priorityqueue);
</script>
</body>
</html>
JavaScript数据结构与算法-使用优先级队列给元素排序
猜你喜欢
转载自blog.csdn.net/weixin_45663697/article/details/109106006
今日推荐
周排行