使用 JavaScript 封装一个二叉堆数据结构

下述代码定义了 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值