最大堆,又称大根堆,大顶堆,JavaScript 实现大根堆的代码。


JavaScript 最大堆完全二叉树结构示意图


最大堆

代码

class MaxHeap {
  constructor () {
    this.heap = []
    this.size = 0
  }

  swap (a, b) {
    const tmp = this.heap[a]
    this.heap[a] = this.heap[b]
    this.heap[b] = tmp
  }

  getParentIndex (index) {
    return index - 1 >> 1
  }

  shiftUp (index) {
    const parentIndex = this.getParentIndex(index)
    if (this.heap[parentIndex] < this.heap[index]) {
      this.swap(parentIndex, index)
      this.shiftUp(parentIndex)
    }
  }

  getLeftIndex (index) {
    return (index << 1) + 1
  }

  getRightIndex (index) {
    return (index << 1) + 2
  }

  shiftDown (index) {
    const leftIndex = this.getLeftIndex(index), rightIndex = this.getRightIndex(index)
    if (this.heap[leftIndex] > this.heap[index]) {
      this.swap(leftIndex, index)
      this.shiftDown(leftIndex)
    }
    if (this.heap[rightIndex] > this.heap[index]) {
      this.swap(rightIndex, index)
      this.shiftDown(rightIndex)
    }
  }

  push (value) {
    this.heap.push(value)
    this.shiftUp(this.size++)
  }

  top () {
    return this.heap[0]
  }

  pop () {
    if (this.size === 0) return null
    if (--this.size === 0) return this.heap.pop()
    const top = this.top()
    this.heap[0] = this.heap.pop()
    this.shiftDown(0)
    return top
  }

  isEmpty() {
    return this.size === 0
  }
}

测试

const maxHeap = new MaxHeap()
for (const a of [3,5,2,4,1]) maxHeap.push(a)
while (!maxHeap.isEmpty()) console.log(maxHeap.pop())
// 5, 4, 3, 2, 1

JavaScript 优先队列代码:支持自定义排序
JavaScript 实现优先队列的代码,自定义排序(最小堆、最大堆都可以),支持数组、矩阵、对象
中位数:求解数据库和数据流中的中位数
中位数 Median 即中数,是有序序列中处于中间位置的数,求解数据库及数据流中的中位数。
广度优先搜索:求解《429. N 叉树的层序遍历》和 《675. 为高尔夫比赛砍树》
广度优先搜索,求解《429. N 叉树的层序遍历》和 《675. 为高尔夫比赛砍树》