自下而上的构造堆

发布于 2024-12-15 04:21:52 字数 371 浏览 4 评论 0原文

我正在解决一个问题,我有 10 个键,并且必须进行自下而上的构造。根据我的书,我应该构建 (n+1)/2 个堆,即底部的 11/2=5.5 个堆。然后第二级为 11/4,第三级为 11/8,依此类推。

问题是我得到这个结果:(

例如使用 'a')

picture of heaps

由于 11/2=5.5,所以我舍入为 6,11/4=2.75 所以 3,11/8=1.375 所以 2,并且11/16=0.6875 所以 1。

即使我不四舍五入,我仍然有一堆奇怪的东西。谁能解释一下我哪里搞砸了?

I'm an working on a question where I have 10 keys and I have to make a bottom up construction. According to my book, I'm supposed to construct (n+1)/2 heaps which is 11/2=5.5 heaps for the bottom. Then 11/4 for the 2nd level, 11/8 for 3rd and so on.

The problem is I get this as result:

(Using 'a' for example)

picture of heaps

Since 11/2=5.5, so I round to 6, 11/4=2.75 so 3, 11/8=1.375 so 2, and 11/16=0.6875 so 1.

Even if I don't round up, I still have a weird heaps. Can anyone explain where I messed up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饮湿 2024-12-22 04:21:52

你搞砸了,因为只有二进制堆中的最后一层才允许不满。包含 10 个元素的堆应该如下所示:

        1
     /     \
    2       3
   /  \    / \
  4    5  6   7
 /\   /
8  9  10

对于自下而上的构造,您不需要过多考虑堆的数量。基本思想是

  1. 没有子节点的节点是平凡的堆。
  2. 如果一个节点有两个堆作为子节点,我们可以通过冒泡操作将其转换为更大的堆。

所以一开始我们知道第 4 层(8、9 和 10)中的节点已经是堆。然后我们可以用它来冒泡第三层中的节点,将它们也变成堆,依此类推。

You messed up because only the last layer in a binary heap is allowed to not be full. A heap with 10 elements should look like this:

        1
     /     \
    2       3
   /  \    / \
  4    5  6   7
 /\   /
8  9  10

As for the bottom up construction you don't need to think too much about the amount of heaps. The basic idea is that

  1. Nodes with no children are trivial heaps.
  2. If a node has two heaps as children we can convert it to a larger heap with a bubbling operation.

So at the start we know that the nodes in the 4th layer (8, 9 and 10) are already heaps. We can then use this to bubble the nodes in the third layer to turn them into heaps as well and so on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文