fre 的最小堆算法

578 阅读1分钟

今天给 fre 重写了最小堆算法,这个算法是用来排序优先级调度的,之前 fre 的实现是抄的 react,代码比较多……

一直想重写,今天才有空……

export function push(heap, node) {
  const i = heap.length
  heap.push(node)
  siftUp(heap, node, i)
}

export function pop(heap) {
  const first = heap[0]
  if (!first) return null
  const last = heap.pop()
  if (last !== first) {
    heap[0] = last
    siftDown(heap, last, 0)
  }
  return first
}

function siftUp(heap, node, i) {
  while (i > 0) {
    const pi = (i - 1) >>> 1
    const parent = heap[pi]
    if (cmp(parent, node) <= 0) return
    heap[pi] = node
    heap[i] = parent
    i = pi
  }
}

function siftDown(heap, node, i) {
  for (;;) {
    const li = i * 2 + 1
    const left = heap[li]
    if (li >= heap.length) return
    const ri = li + 1
    const right = heap[ri]
    const ci = ri < heap.length && cmp(right, left) < 0 ? ri : li
    const child = heap[ci]
    if (cmp(child, node) > 0) return
    heap[ci] = node
    heap[i] = child
    i = ci
  }
}

function cmp(a, b) {
  return a.dueTime - b.dueTime
}

export function peek(heap) {
  return heap[0] || null
}

以上,我能写出来的目前性价比最高的堆排了,比之前版本减少了一半的代码量,测试全部 pass

地址在这里:github.com/yisar/fre/b…

其实我平时刷算法并不多,但是我的代码需要用到一个算法的时候,我还是很愿意去研究并找出最佳性价比的实现

最佳性价比 = 最小的代码量 / 最差的性能

最近比较忙,我们回见~