返回

用 JS 实现高效二叉堆

前端







**二叉堆:概念与应用** 

二叉堆是一种树形数据结构,它满足以下两个性质:

* **堆性质:** 每个节点的值都大于或等于其子节点的值。
* **完全二叉树:** 除了最后一层之外,所有层都完全填充。

这种结构使得二叉堆具有快速插入和删除元素的特性,使其成为优先队列和堆排序等算法的理想选择。

**JS 中的二叉堆实现** 

**1. 创建二叉堆类** 

```js
class BinaryHeap {
  constructor() {
    this.heap = [];
  }

2. 插入元素

insert(value) {
  this.heap.push(value);
  this.bubbleUp(this.heap.length - 1);
}

该方法将元素插入堆的末尾,然后使用 bubbleUp 方法将其调整到适当的位置。

3. bubbleUp 方法

bubbleUp(index) {
  while (index > 0) {
    const parentIndex = Math.floor((index - 1) / 2);
    if (this.heap[parentIndex] < this.heap[index]) {
      [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
    }
    index = parentIndex;
  }
}

此方法将元素向上移动,直到满足堆性质。

4. 删除根元素(最小值)

remove() {
  if (this.heap.length === 0) {
    return null;
  }
  const root = this.heap[0];
  this.heap[0] = this.heap[this.heap.length - 1];
  this.heap.pop();
  this.bubbleDown(0);
  return root;
}

此方法删除堆顶部的根元素(最小值),并使用 bubbleDown 方法重新调整堆。

5. bubbleDown 方法

bubbleDown(index) {
  while (true) {
    const leftChildIndex = index * 2 + 1;
    const rightChildIndex = index * 2 + 2;
    let maxIndex = index;

    if (leftChildIndex < this.heap.length && this.heap[leftChildIndex] > this.heap[maxIndex]) {
      maxIndex = leftChildIndex;
    }

    if (rightChildIndex < this.heap.length && this.heap[rightChildIndex] > this.heap[maxIndex]) {
      maxIndex = rightChildIndex;
    }

    if (maxIndex === index) {
      break;
    }

    [this.heap[index], this.heap[maxIndex]] = [this.heap[maxIndex], this.heap[index]];
    index = maxIndex;
  }
}

此方法将元素向下移动,直到满足堆性质。

用例

二叉堆在 JS 中可以广泛应用于:

  • 堆排序:一种高效的排序算法。
  • 优先队列:用于管理具有优先级的任务或事件。
  • 查找中位数:通过维护一个最大堆和一个最小堆,可以在 O(log n) 时间内找到一个有序数组的中位数。

结论

本指南提供了在 JS 中实现二叉堆的分步指南,涵盖了插入、删除、排序和用例等各个方面。通过掌握这一高效的数据结构,你可以提升 JS 代码的性能和效率。