27. React源码之scheduler--最小堆

最小堆特点是一棵完全二叉树,父节点小于子节点;采用数组存储。

代码详情

function push(heap, node) {
  const index = heap.length;
  heap.push(node);
  siftUp(heap, node, index);
}
function peek(heap) {
  return heap.length === 0 ? null : heap[0];
}
function pop(heap) {
  if (heap.length === 0) {
    return null;
  }
  const first = heap[0];
  const last = heap.pop();
  if (last !== first) {
    heap[0] = last;
    siftDown(heap, last, 0);
  }
  return first;
}
function siftUp(heap, node, i) {
  let index = i;
  while (index > 0) {
    const parentIndex = (index - 1) >>> 1;
    const parent = heap[parentIndex];
    if (compare(parent, node) > 0) {
      heap[parentIndex] = node;
      heap[index] = parent;
      index = parentIndex;
    } else {
      return;
    }
  }
}
function siftDown(heap, node, i) {
  let index = i;
  const length = heap.length;
  const halfLength = length >>> 1;
  while (index < halfLength) {
    const leftIndex = (index + 1) * 2 - 1;
    const left = heap[leftIndex];
    const rightIndex = leftIndex + 1;
    const right = heap[rightIndex];
    if (compare(left, node) < 0) {
      if (rightIndex < length && compare(right, left) < 0) {
        heap[index] = right;
        heap[rightIndex] = node;
        index = rightIndex;
      } else {
        heap[index] = left;
        heap[leftIndex] = node;
        index = leftIndex;
      }
    } else if (rightIndex < length && compare(right, node) < 0) {
      heap[index] = right;
      heap[rightIndex] = node;
      index = rightIndex;
    } else {
      return;
    }
  }
}
function compare(a, b) {
  const diff = a.sortIndex - b.sortIndex;
  return diff !== 0 ? diff : a.id - b.id;
}

const heap = [];
let id = 0;
push(heap, { sortIndex: 7, id: id++ });
push(heap, { sortIndex: 2, id: id++ });
push(heap, { sortIndex: 1, id: id++ });
push(heap, { sortIndex: 3, id: id++ });
pop(heap);
console.log(heap);
// heap
// [
//   { sortIndex: 2, id: 1 },
//   { sortIndex: 3, id: 3 },
//   { sortIndex: 7, id: 0 }
// ]

知识点

  1. 插入节点:将待插入节点放到数组末尾向上调整;
  2. 删除节点:数组第一个元素是最小节点,将最后一个元素放到最前面,然后向下调整;

参考

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 二叉堆定义 二叉堆是一种特殊的堆, 二叉堆是完全二叉树或者近似完全二叉树. 二叉堆满足堆特性: 父节点的键值总是保...
    爱吃鱼的KK阅读 897评论 0 2
  • 什么是二叉堆 二叉堆是一种特殊的堆,它的父节点的值总是大于等于(或小于等于它的子节点值,称作小顶堆),这种堆叫做大...
    努力护肤的程序媛阅读 549评论 0 0
  • 简介 堆是一种基于完全二叉树的数据结构.完全二叉树: 每个节点最多有两个子节点(二叉)除了最底层, 其他每一层都必...
    是杨不是阳羊扬阅读 3,348评论 0 4
  • 二叉搜索树: 又称二叉排序树,二叉查找树 满足以下性质: 1)没有键值相等的节点。 2)若左子树不为空,左子树上节...
    一川烟草i蓑衣阅读 9,784评论 0 0
  • 堆 // 堆实际上是一个完全二叉树// 如果用0是堆的根节点,那么:// 最子节点是20+1,右子节点是20+2/...
    月下蓑衣江湖夜雨阅读 235评论 0 0