/**
* 最大堆:完全二叉树,用数组保存,
* 从数组下标 0 开始,即 父元素节点为 i, 子元素节点为 2*i+1, 2*i+2
* 子节点为 i(i >= 1) , 则父节点为 (i-1)/2
*
* count: 最大堆的有效数据长度
*/
module.exports = (function () {
const items = new WeakMap();
class MaxHeap {
constructor(size) {
this.data = [];
this.count = 0;
}
swap(i1, i2) {
[this.data[i1], this.data[i2]] = [this.data[i2], this.data[i1]];
}
shiftUp(k) {
while (k >= 1) {
let dad = Math.floor((k-1) / 2);
if (this.data[dad] < this.data[i]) {
this.swap(dad, i);
k = dad;
}
}
}
shiftDown(k) {
// k 为父节点,与子节点比较
while ((2*k+1) < this.count) {
let child = 2*k+1;
if (child + 1 < this.count && this.data[child+1] > this.data[child]) {
child += 1;
}
if (this.data[k] < this.data[child]) {
this.swap(k, child);
k = child;
} else {
break;
}
}
}
/**
* 往最大堆中插入一条数据
* @param item
*/
insert(item) {
this.data[this.count++] = item;
this.shiftUp(this.data.length - 1);
}
/**
* 删除最大堆的最大值,并保持最大堆的性质
*/
extractMax() {
// 交换第一个和最后一个数
const res = this.data[this.count - 1];
this.swap(this.count, 0);
this.count--;
this.shiftDown(0);
return res;
}
size() {
return this.size;
}
}
})();
数据结构与算法--最大堆
最新推荐文章于 2023-04-05 21:23:41 发布