在JavaScript中实现一个递归的最大堆(maxHeap)是一种常见的数据结构操作,它允许我们高效地获取和调整堆中的最大元素。最大堆是一种特殊的完全二叉树,其中每个父节点的值都大于或等于其子节点的值。
以下是一个简单的JavaScript实现,包括插入和提取最大元素的操作:
class MaxHeap {
constructor() {
this.heap = [];
}
// 获取父节点索引
getParentIndex(index) {
return Math.floor((index - 1) / 2);
}
// 获取左子节点索引
getLeftChildIndex(index) {
return 2 * index + 1;
}
// 获取右子节点索引
getRightChildIndex(index) {
return 2 * index + 2;
}
// 交换两个元素
swap(index1, index2) {
[this.heap[index1], this.heap[index2]] = [this.heap[index2], this.heap[index1]];
}
// 插入元素
insert(value) {
this.heap.push(value);
this.bubbleUp(this.heap.length - 1);
}
// 上浮操作
bubbleUp(index) {
while (index > 0 && this.heap[index] > this.heap[this.getParentIndex(index)]) {
this.swap(index, this.getParentIndex(index));
index = this.getParentIndex(index);
}
}
// 提取最大元素
extractMax() {
if (this.heap.length === 1) return this.heap.pop();
const max = this.heap[0];
this.heap[0] = this.heap.pop();
this.bubbleDown(0);
return max;
}
// 下沉操作
bubbleDown(index) {
let largestIndex = index;
const leftChildIndex = this.getLeftChildIndex(index);
const rightChildIndex = this.getRightChildIndex(index);
if (leftChildIndex < this.heap.length && this.heap[leftChildIndex] > this.heap[largestIndex]) {
largestIndex = leftChildIndex;
}
if (rightChildIndex < this.heap.length && this.heap[rightChildIndex] > this.heap[largestIndex]) {
largestIndex = rightChildIndex;
}
if (largestIndex !== index) {
this.swap(index, largestIndex);
this.bubbleDown(largestIndex);
}
}
}
// 使用示例
const maxHeap = new MaxHeap();
maxHeap.insert(3);
maxHeap.insert(4);
maxHeap.insert(9);
maxHeap.insert(5);
maxHeap.insert(2);
console.log(maxHeap.extractMax()); // 输出: 9
console.log(maxHeap.extractMax()); // 输出: 5
bubbleUp
和bubbleDown
方法可以恢复堆属性。通过上述实现,你可以有效地管理和操作最大堆,适用于多种需要高效处理最大元素的场景。
云+社区沙龙online [国产数据库]
TVP技术夜未眠
云+社区沙龙online第5期[架构演进]
腾讯数字政务云端系列直播
云+社区技术沙龙[第17期]
领取专属 10元无门槛券
手把手带您无忧上云