function PriorityQueue(maxLength = null,sortFlag="min") {
this.val = [];
this.maxLength = maxLength;//队列的最大长度
this.sortFlag = sortFlag;//最小队列(min),最大队列(max)
return this;
}
//入队元素(在尾部加入新元素后,做上浮调整)
PriorityQueue.prototype.enQueue = function (val) {
this.val.push(val);
this.upAdjust();
}
//删除元素
PriorityQueue.prototype.delQueue = function () {
if (this.val.length === 0) {
throw new Error('队列已经是空的')
}
//获取堆顶元素
let head = this.val[0];
//让最后一个元素移动到堆顶;
this.val[0] = this.val[this.val.length - 1];
//下沉调整
this.downAdjust();
return head;
}
//上浮调整
PriorityQueue.prototype.upAdjust = function () {
let childIndex = this.val.length - 1;//从最后一个元素开始调整
let parentIndex = Math.floor((childIndex - 1) / 2)> 0 ? Math.floor((childIndex - 1) / 2) : 0;//左节点:2*parent + 1
// temp用于保存插入的节点值,用于最后的赋值
let temp = this.val[childIndex];
if (this.sortFlag === "min") {//最小优先队列
while (childIndex > 0 && temp < this.val[parentIndex]) {
this.val[childIndex] = this.val[parentIndex];
childIndex = parentIndex;
parentIndex = Math.floor(parentIndex / 2) > 0 ? Math.floor(parentIndex / 2) : 0;
}
this.val[childIndex] = temp;
} else {//最大优先队列
while (childIndex > 0 && temp > this.val[parentIndex]) {
this.val[childIndex] = this.val[parentIndex];
childIndex = parentIndex;
parentIndex = Math.floor(parentIndex / 2) > 0 ? Math.floor(parentIndex / 2):0;
}
this.val[childIndex] = temp;
}
}
//下沉调整
PriorityQueue.prototype.downAdjust = function () {
let parentIndex = 0;//从第一个元素开始做下沉调整
let temp = this.val[parentIndex];
let childIndex = 2 * parentIndex + 1;//左孩子节点
while (childIndex < this.val.length) {
if (this.sortFlag === "min") {//最小优先队列
if (childIndex + 1 < this.val.length && this.val[childIndex + 1] < this.val[childIndex]) {
childIndex ++;
}
//父节点小于任意个子节点,直接跳出
if (temp < this.val[childIndex]) break;
this.val[parentIndex] = this.val[childIndex];
parentIndex = childIndex;
childIndex = 2 * parentIndex + 1;
} else {//最大优先队列
if (childIndex + 1 < this.val.length && this.val[childIndex + 1] > this.val[childIndex]) {
childIndex ++
}
//父节点最大,直接跳出
if (temp > this.val[childIndex]) break;
this.val[parentIndex] = this.val[childIndex];
parentIndex = childIndex;
childIndex = 2 * parentIndex + 1;
}
}
this.val[parentIndex] = temp;
}
let queue = new PriorityQueue(3, "max");
queue.enQueue(1)
queue.enQueue(5)
queue.enQueue(8)
queue.enQueue(4)
console.log(queue.val) // [ 8, 4, 5, 1 ]
let min_queue = new PriorityQueue(3, "min");
min_queue.enQueue(1)
min_queue.enQueue(5)
min_queue.enQueue(8)
min_queue.enQueue(4)
console.log(min_queue.val)//[ 1, 4, 8, 5 ]
javaScript实现最大最小优先队列
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。