下述代码定义了 BinaryHeap
类,其中:
constructor
方法初始化一个空数组heap
作为堆的存储结构。insert
方法接受一个值,将其添加到堆中,并调用bubbleUp
方法维护堆的性质。bubbleUp
方法将新添加的值向上冒泡,直到其父节点的值大于等于它。extractMax
方法返回堆中最大的值,并将其删除。同时,将堆的最后一个元素移到堆顶,并调用sinkDown
方法维护堆的性质。sinkDown
方法将堆顶的值向下沉,直到其子节点的值小于等于它。
class BinaryHeap {
constructor() {
this.heap = [];
}
insert(value) {
this.heap.push(value);
this.bubbleUp();
}
bubbleUp() {
let index = this.heap.length - 1;
const element = this.heap[index];
while (index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
let parent = this.heap[parentIndex];
if (element <= parent) break;
this.heap[parentIndex] = element;
this.heap[index] = parent;
index = parentIndex;
}
}
extractMax() {
const max = this.heap[0];
const end = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = end;
this.sinkDown(0);
}
return max;
}
sinkDown(index) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let maxIndex = index;
const length = this.heap.length;
if (leftChildIndex < length && this.heap[leftChildIndex] > this.heap[maxIndex]) {
maxIndex = leftChildIndex;
}
if (rightChildIndex < length && this.heap[rightChildIndex] > this.heap[maxIndex]) {
maxIndex = rightChildIndex;
}
if (maxIndex !== index) {
[this.heap[maxIndex], this.heap[index]] = [this.heap[index], this.heap[maxIndex]];
this.sinkDown(maxIndex);
}
}
}
使用时,可以先创建一个 BinaryHeap
实例,然后调用其方法进行操作,例如:
const heap = new BinaryHeap();
heap.insert(5);
heap.insert(3);
heap.insert(8);
heap.insert(1);
console.log(heap.extractMax()); // 8
console.log(heap.extractMax()); // 5
console.log(heap.extractMax()); // 3
console.log(heap.extractMax()); // 1