最小堆,又称为小根堆,小顶堆,实现 JavaScript 版小根堆的代码。

最小堆的完全二叉树结构示意图

最小堆

代码

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

  swap(i, j) {
    const tmp = this.heap[i]
    this.heap[i] = this.heap[j]
    this.heap[j] = 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)
    const 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 tmp = this.heap[0]
    this.heap[0] = this.heap.pop()
    this.shiftDown(0)
    return tmp
  }

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

测试

const minHeap = new MinHeap()
for (const a of [3,5,2,4,1]) minHeap.push(a)
while (!minHeap.isEmpty()) console.log(minHeap.pop())
// [1, 2, 3, 4, 5]
JavaScript 优先队列代码:支持自定义排序
JavaScript 实现优先队列的代码,自定义排序(最小堆、最大堆都可以),支持数组、矩阵、对象
JavaScript 最大堆(大根堆、大顶堆)代码
最大堆,又称大根堆,大顶堆,JavaScript 实现大根堆的代码。
中位数:求解数据库和数据流中的中位数
中位数 Median 即中数,是有序序列中处于中间位置的数,求解数据库及数据流中的中位数。