返回

在 JavaScript 中,充分利用堆数据结构的妙处:从小到大排列数据

前端

简介:堆数据结构概览

堆是一种特殊的完全二叉树,其中的每个节点都满足以下性质:

  • 父节点总是大于或等于子节点(最大堆)
  • 父节点总是小于或等于子节点(最小堆)

应用场景:排序与优先级队列

堆数据结构广泛应用于各种场景,其中最常见的两大应用领域是排序和优先级队列。

  1. 排序:
    堆排序是一种高效的排序算法,其时间复杂度为 O(n log n),对于大数据集来说非常高效。

  2. 优先级队列:
    优先级队列是一种数据结构,它允许以优先级顺序访问元素。堆是一种天然的优先级队列,因为堆顶元素始终是优先级最高的元素。

实现:JavaScript 中的堆

JavaScript 中,可以使用数组来实现堆数据结构。

  1. 创建堆:
    首先,创建一个空数组作为堆。

  2. 插入元素:
    要将元素插入堆中,请执行以下步骤:

  • 将元素添加到数组的末尾。
  • 将该元素向上移动,直到满足堆的性质(即父节点大于或等于子节点)。
  1. 删除元素:
    要从堆中删除元素,请执行以下步骤:
  • 将堆顶元素(优先级最高的元素)替换为数组中的最后一个元素。
  • 将堆顶元素向下移动,直到满足堆的性质。

示例代码:

class Heap {
  constructor() {
    this.heap = [];
  }

  insert(value) {
    this.heap.push(value);
    this.heapifyUp();
  }

  heapifyUp() {
    let index = this.heap.length - 1;

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

  remove() {
    if (this.heap.length === 0) {
      return null;
    }

    const maxValue = this.heap[0];
    this.heap[0] = this.heap.pop();
    this.heapifyDown();

    return maxValue;
  }

  heapifyDown() {
    let index = 0;

    while (index < this.heap.length) {
      const leftChildIndex = 2 * index + 1;
      const rightChildIndex = 2 * index + 2;

      let largestIndex = 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);
        index = largestIndex;
      } else {
        break;
      }
    }
  }

  swap(index1, index2) {
    const temp = this.heap[index1];
    this.heap[index1] = this.heap[index2];
    this.heap[index2] = temp;
  }
}

const heap = new Heap();
heap.insert(10);
heap.insert(5);
heap.insert(15);
heap.insert(3);
heap.insert(7);
heap.insert(18);

console.log(heap.heap); // [18, 15, 10, 7, 5, 3]

console.log(heap.remove()); // 18
console.log(heap.remove()); // 15
console.log(heap.remove()); // 10
console.log(heap.remove()); // 7
console.log(heap.remove()); // 5
console.log(heap.remove()); // 3

console.log(heap.heap); // []

结语

掌握了堆数据结构的原理与应用后,您将能够更轻松地解决复杂的数据管理问题。JavaScript 中的堆实现为各种场景提供了高效的数据处理解决方案,让您在编程实践中游刃有余。