javascript - 二叉堆 - 为什么删除函数需要调用 bubbleUp 方法?

标签 javascript binary heap push

我一直在通过 eloquentjavascript 网站学习 JavaScript,并得到了一些我似乎无法理解的代码:

remove: function(node) {
    var length = this.content.length;
    // To remove a value, we must search through the array to find
    // it.
    for (var i = 0; i < length; i++) {
      if (this.content[i] != node) continue;
      // When it is found, the process seen in 'pop' is repeated
      // to fill up the hole.
      var end = this.content.pop();
      // If the element we popped was the one we needed to remove,
      // we're done.
      if (i == length - 1) break;
      // Otherwise, we replace the removed element with the popped
      // one, and allow it to float up or sink down as appropriate.
      this.content[i] = end;
      this.bubbleUp(i);
      this.sinkDown(i);
      break;
    }
  },

我的问题是 - 为什么这个函数需要调用 bubbleUp()? 如果 end 是二叉堆上的最后一个值,并且每个推送到堆上的值在通过 push() 方法添加时都会调用 bubbleUp,那么 end 值的分数怎么可能比 i 处的值低呢?我对数据结构很陌生,似乎无法弄清楚这一点。

最佳答案

想象一个像这样的最小堆:

       1
   10      2
 18  20  3   4

现在,假设您删除了 20。您的代码基本上将 4 固定在其位置。

       1
   10      2
 18   4  3

由于 4 < 10,它必须冒泡才能满足最小堆的要求。

关于javascript - 二叉堆 - 为什么删除函数需要调用 bubbleUp 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22105063/

相关文章:

javascript - 切换单个表同时隐藏其他表

perl - 以字节/位的形式查看 Perl 变量

Java 整数 parseInt 错误

database - 内部排序,使用两个堆解释的锦标赛排序算法

c - C中Heap实现中的BubbleUp方法

javascript - 如何在 ReactJS JSX 中执行嵌套的 if else 语句?

javascript - 使用变量指定 jquery 选择器

javascript - 如何从列表表 tr 中获取值

java - Largest Java Short (32767) 加 1 不转负?

algorithm - 堆排序伪代码算法