结合React源码,五分钟带你掌握优先队列

开发 前端
最近写一个需求用到了优先队列和二叉堆的相关知识,借此机会梳理了一些二叉堆的相关知识分享给大家。

最近写一个需求用到了优先队列和二叉堆的相关知识,借此机会梳理了一些二叉堆的相关知识分享给大家。

什么是优先队列

  • 优先队列是数据结构中的基础概念,与队列先进先出(FIFO)的出队顺序不同的是 ,它的出队顺序与元素的优先级相关。
  • 例如 React 的时间分片(React Fiber),它将渲染任务分了优先级,出队的顺序与任务的“重要程度”存在关系,那么满足这种情况的数据结构就是 优先队列 。

优先队列的操作

  • 插入:在优先队列中插入元素,并使队列“有序”
  • 删除最大/最小值:删除并返回最大/最小的元素,并使队列“有序”
  • 查找最大/最小关键字:查找最大/最小的值

优先队列的实现比较

 

优先队列可以由以上多种方式实现,而优先队列的主要操作是插入和删除,其中二叉搜索树和二叉堆这两项操作的时间复杂度均为 logn ,但二叉树在多次删除之后容易导致树的倾斜,同时查找成本也高于二叉堆,所以最终二叉堆是比较符合实现优先队列的数据结构。

二叉堆

在二叉堆中数组中,要保证每个元素都小于(大于)或等于另外两个特定位置的元素。例如下图的树中,父节点总是小于或等于子节点。

对于二叉堆有如下性质:

  • 节点 k 的父节点下标为 k / 2(向下取整)
  • 已某节点为根节点的子树,该节点是这颗树的极值

二叉堆的操作

插入

二叉堆的插入非常简单,只需要在二叉堆的最后添加要插入的内容,并将其“上浮”到正确位置。

尝试在上面的二叉堆中插入新元素 9,过程如下:

在尾部插入元素 9,与父节点进行对比,有序性被破坏,与父元素替换位置。

替换成功后,继续上一轮操作,与父节点进行对比,仍然无法满足有序性,继续调换位置。

再次替换后符合。

程序框架

 

  1. function push { 
  2.   * 在堆尾部添加元素 
  3.   * 执行上浮循环 
  4.     * 与父元素对比大小,将较大的放在父节点位置 
  5.  
  6.   return minItem 

实现

 

  1. function push(heap: Heap, node: Node): void { 
  2.   const index = heap.length; 
  3.   heap.push(node); // 在堆尾部添加元素 
  4.   siftUp(heap, node, index); // 进行上浮操作 
  5.  
  6. function siftUp(heap, node, i) { 
  7.   let index = i; 
  8.   while (true) { 
  9.     const parentIndex = (index - 1) >>> 1; // 父节点位置: parentIndex = childIndex / 2 
  10.     const parent = heap[parentIndex]; 
  11.     if (parent !== undefined && compare(parent, node) > 0) { 
  12.       // The parent is larger. Swap positions. 
  13.       heap[parentIndex] = node; 
  14.       heap[index] = parent; 
  15.       index = parentIndex; 
  16.     } else { 
  17.       // The parent is smaller. Exit. 
  18.       return
  19.     } 
  20.   } 

删除

取出根节点的值对比插入稍微复杂一点,归纳起来可以分为三步:

  • 取出根节点的值
  • 将最后一个元素与根节点进行替换,并删除最后一个元素
  • 下沉

取出根节点。

将最后一个元素与根节点调换,并删除。对比发现有序性被破坏,进行对调。

完成删除。

程序框架

 

  1. function pop { 
  2.   * 设定 minItem 保存根节点 
  3.   * 取出最后一个节点与根节点替换,并删除最后一个节点 
  4.   * 执行下沉循环 
  5.     * 将根元素与左右子节点对比,挑选较小的与父节点替换位置 
  6.  
  7.   return minItem 

实现

 

  1. export function pop(heap: Heap): Node | null { 
  2.   const first = heap[0]; // 取出根节点 
  3.   if (first !== undefined) { 
  4.     const last = heap.pop(); // 取出最后一位元素,并删除 
  5.     if (last !== first) { 
  6.       heap[0] = last; // 与根节点对调 
  7.       siftDown(heap, last, 0); // 下沉 
  8.     } 
  9.     return first
  10.   } else { 
  11.     return null
  12.   } 
  13.  
  14. function siftDown(heap, node, i) { 
  15.   let index = i; 
  16.   const length = heap.length; 
  17.   while (index < length) { 
  18.     const leftIndex = (index + 1) * 2 - 1; 
  19.     const left = heap[leftIndex]; 
  20.     const rightIndex = leftIndex + 1; 
  21.     const right = heap[rightIndex]; 
  22.  
  23.     // If the left or right node is smaller, swap with the smaller of those. 
  24.     // 寻找左右儿子较小的那一个替换 
  25.     if (left !== undefined && compare(left, node) < 0) { //左子节点小于根节点 
  26.       if (right !== undefined && compare(rightleft) < 0) { 
  27.         heap[index] = right
  28.         heap[rightIndex] = node; 
  29.         index = rightIndex; 
  30.       } else { 
  31.         heap[index] = left
  32.         heap[leftIndex] = node; 
  33.         index = leftIndex; 
  34.       } 
  35.     } else if (right !== undefined && compare(right, node) < 0) { // 左子节点大于根节点,右子节点小于根节点 
  36.       heap[index] = right
  37.       heap[rightIndex] = node; 
  38.       index = rightIndex; 
  39.     } else { 
  40.       // Neither child is smaller. Exit. 
  41.       return
  42.     } 
  43.   } 

以下是 react 源码中 scheduler/src/SchedulerMinHeap.js 关于最小堆的完整实现:

 

  1. /** 
  2.  * Copyright (c) Facebook, Inc. and its affiliates. 
  3.  * 
  4.  * This source code is licensed under the MIT license found in the 
  5.  * LICENSE file in the root directory of this source tree. 
  6.  * 
  7.  * @flow strict 
  8.  */ 
  9.  
  10. // 定义最小堆极其元素,其中 sortIndex 为最小堆对比的 key,若 sortIndex 相同,则对比 id 
  11. type Heap = Array<Node>; 
  12. type Node = {| 
  13.   id: number, 
  14.   sortIndex: number, 
  15. |}; 
  16.  
  17. // 入队操作,在入队完成之后进行“上浮” 
  18. export function push(heap: Heap, node: Node): void { 
  19.   const index = heap.length; 
  20.   heap.push(node); 
  21.   siftUp(heap, node, index); 
  22.  
  23. // 查找最大值 
  24. export function peek(heap: Heap): Node | null { 
  25.   const first = heap[0]; 
  26.   return first === undefined ? null : first
  27.  
  28. // 删除并返回最大值 
  29. export function pop(heap: Heap): Node | null { 
  30.   const first = heap[0]; // 取出根节点(哨兵) 
  31.   if (first !== undefined) { 
  32.     const last = heap.pop(); // 取出最后一位元素,并删除 
  33.     if (last !== first) { // 头尾并没有对撞 
  34.       heap[0] = last; // 与根节点对调 
  35.       siftDown(heap, last, 0); // 下沉 
  36.     } 
  37.     return first
  38.   } else { 
  39.     return null
  40.   } 
  41.  
  42. // 上浮,调整树结构 
  43. function siftUp(heap, node, i) { 
  44.   let index = i; 
  45.   while (true) { 
  46.     const parentIndex = (index - 1) >>> 1; // 父节点位置: parentIndex = childIndex / 2,此处使用位操作,右移一位 
  47.     const parent = heap[parentIndex]; 
  48.     if (parent !== undefined && compare(parent, node) > 0) { // 对比父节点和子元素的大小 
  49.       // The parent is larger. Swap positions. 
  50.       heap[parentIndex] = node; // 若父节点较大,则更换位置 
  51.       heap[index] = parent; 
  52.       index = parentIndex; 
  53.     } else { 
  54.       // The parent is smaller. Exit. 
  55.       return
  56.     } 
  57.   } 
  58.  
  59. // 下沉,调整树结构 
  60. function siftDown(heap, node, i) { 
  61.   let index = i; 
  62.   const length = heap.length; 
  63.   while (index < length) { 
  64.     const leftIndex = (index + 1) * 2 - 1; 
  65.     const left = heap[leftIndex]; 
  66.     const rightIndex = leftIndex + 1; 
  67.     const right = heap[rightIndex]; 
  68.  
  69.     // If the left or right node is smaller, swap with the smaller of those. 
  70.     // 寻找左右儿子较小的那一个替换 
  71.     if (left !== undefined && compare(left, node) < 0) { 
  72.       if (right !== undefined && compare(rightleft) < 0) { // 左子节点小于根节点 
  73.         heap[index] = right
  74.         heap[rightIndex] = node; 
  75.         index = rightIndex; 
  76.       } else { 
  77.         heap[index] = left
  78.         heap[leftIndex] = node; 
  79.         index = leftIndex; 
  80.       } 
  81.     } else if (right !== undefined && compare(right, node) < 0) { // 左子节点大于根节点,右子节点小于根节点 
  82.       heap[index] = right
  83.       heap[rightIndex] = node; 
  84.       index = rightIndex; 
  85.     } else { 
  86.       // Neither child is smaller. Exit. 
  87.       return
  88.     } 
  89.   } 
  90.  
  91. function compare(a, b) { 
  92.   // Compare sort index firstthen task id. 
  93.   const diff = a.sortIndex - b.sortIndex; 
  94.   return diff !== 0 ? diff : a.id - b.id; 

堆排序

利用最大/最小堆的特性,我们很容易就能实现对数组的排序,重复执行 pop 就能进行升序排列,如果要降序,使用最大堆即可,该操作时间复杂度为 nlogn 。

多叉堆

为了追求更优的时间复杂度,我们可以将二叉堆改为多叉堆实现,下图为一个三叉堆:

与二叉堆不同的是对于含有 N 个元素的 d 叉堆(通常情况下 d >= 2),随着 d 的增加,树高 K = logdN 的斜率会下降,然而 d 越大,删除操作的成本会更高。所以子元素不是越多越好,通常情况下三叉堆和四叉堆的应用会比较常见。

在libev中有这么一段注释 https://github.com/enki/libev/blob/master/ev.c#L2227,他提及了四叉树相比二叉堆来说缓存更加友好。 根据benchmark,在 50000+ 个 watchers 的场景下,四叉树会有 5% 的性能优势。

 

  1. /* 
  2.  * at the moment we allow libev the luxury of two heaps, 
  3.  * a small-code-size 2-heap one and a ~1.5kb larger 4-heap 
  4.  * which is more cache-efficient. 
  5.  * the difference is about 5% with 50000+ watchers. 
  6.  */ 

同样 Go 语言中的定时器的 timersBucket 的数据结构也采用了最小四叉堆。

 

 


 

结语

多叉堆,例如四叉堆更加适合数据量大,对缓存要求友好对场景。二叉堆适用数据量比较小且频繁插入和删除的场景。通常情况下二叉堆可以满足大部分情况下的需求,如果编写底层代码,并且对性能有更高的要求,那么可以考虑多叉堆实现优先队列。

责任编辑:未丽燕 来源: ZooTeam Blog
相关推荐

2021-06-07 09:51:22

原型模式序列化

2021-10-19 07:27:08

HTTP代理网络

2009-11-17 14:50:50

Oracle调优

2019-12-23 16:42:44

JavaScript前端开发

2022-05-30 07:51:13

数据库MySQLQPS

2009-11-05 10:55:22

Visual Stud

2021-01-11 09:33:37

Maven数目项目

2020-02-19 19:26:27

K8S开源平台容器技术

2017-01-10 09:07:53

tcpdumpGET请求

2020-04-01 16:30:32

TCP互联网Linux

2018-01-08 16:19:04

微信程序轮播图

2018-06-26 09:37:07

时序数据库FacebookNoSQL

2022-06-17 08:05:28

Grafana监控仪表盘系统

2021-10-20 06:58:10

工具低代码无代码

2022-08-04 13:27:35

Pythonopenpyxl

2009-11-16 10:53:30

Oracle Hint

2017-04-25 12:07:51

AndroidWebViewjs

2024-03-21 09:51:22

Python爬虫浏览网站

2020-09-14 11:30:26

HTTP3运维互联网

2021-06-18 07:34:12

Kafka中间件微服务
点赞
收藏

51CTO技术栈公众号