03-优先级队列

109 阅读2分钟

主要特点

  1. 普通队列插入元素会从队尾添加,并且只能从队首删除,而且要等前面元素都处理完才能处理
  2. 优先级队列插入元素时会考虑优先级,和其他元素进行优先级比较,再放入正确的位置
  1. 每个元素包括数据和优先级
  2. 添加时根据优先级放入正确的位置

生活场景

  • 机场登机,头等舱,经济舱
  • 去医院的急诊号比其他优先
  • 计算机中也会用优先级队列进行任务顺序的排列,决定该线程在队列中被处理的次序

主要实现思路

  1. 将数据和优先级封装成一个元素
// 封装元素
class QueueElement {
  constructor(element,priority) {
    this.element = element
    this.priority = priority
  }
}
  1. 添加元素时,将要添加的元素优先级和已存在的元素优先级进行比较,获得正确位置
			// 插入元素
			enqueue(element,priority) {
				// 1、传入的数据和优先级创建一个队列元素实例对象
				let queueElement = new QueueElement(element,priority)
				// 2、将元素插入到对应的位置

				if(this.isEmpty()) {
					this.items.push(queueElement)
				} else {
					let added = false
					// 遍历已有队列,逐个对比元素的优先级,找到比此元素优先级大的,插入到前面
					for(let i = 0; i < this.size(); i++) {
						if(this.items[i].priority > queueElement.priority) {
							this.items.splice(i,0,queueElement)
							added = true
							break
						}
					}
					if(!added) {
					this.items.push(queueElement)
				}
				}
				
			}
  1. 其余代码和之前的队列一样
			// 封装优先级队列
		class PriorityQueue {
			constructor() {
				this.items = []
			}
			// 插入元素
			enqueue(element,priority) {
				// 1、传入的数据和优先级创建一个队列元素实例对象
				let queueElement = new QueueElement(element,priority)
				// 2、将元素插入到对应的位置

				if(this.isEmpty()) {
					this.items.push(queueElement)
				} else {
					let added = false
					// 遍历已有队列,逐个对比元素的优先级,找到比此元素优先级大的,插入到前面
					for(let i = 0; i < this.size(); i++) {
						if(this.items[i].priority > queueElement.priority) {
							this.items.splice(i,0,queueElement)
							added = true
							break
						}
					}
					if(!added) {
					this.items.push(queueElement)
				}
				}
				
			}
				// 	// 队首移除
			dequeue() {
				return this.items.shift()
			}
			// 访问队首
			front() {
				return this.items[0]
			}
			// 队列大小
			size() {
				return this.items.length;
			}
			// 判断队空
			isEmpty() {
				return this.size() === 0
				
			}
			// 输出队列
			toString() {
					let res = ''
					for (var i = 0; i < this.size(); i++) {
						res +=  this.items[i].element + ':' + this.items[i].priority + ','
					}
					console.log(res)
				}
		}