对 heapify 进行更严格的绑定
我想使用 siftdown 方法计算 heapify 上更严格的界限,因此我按如下方式进行:
在每个级别 i
上,该级别上的每个键都可以转到叶级别 h
(其中h 是树的高度)在最坏的情况下。
由于第 i 层有 2i 个节点,因此完成的总工作为
Σ0≤i≤h (h - i ) * 2i
但我无法继续下去。我知道它必须达到 O(n) 但我无法达到它。请帮我解决这个问题。
I want to calculate the tighter bound on heapify using siftdown approach so I proceeded as follows :
At each level i
, each key on that level can go to leaf level h
(where h is height of tree) in the worst case.
As there are 2i nodes at level i, so total work done is
∑0≤i≤h (h - i ) * 2i
But I couldn't proceed further. I know it has to come O(n) but I couldn't reach it. Please help me solving this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
S = Σ0≤i≤h (h - i ) * 2i
S = h + 2(h - 1) + 4(h - 2) + .. . + 2h - 1 ... (1)
两边都乘以 2,2S
= 2h + 4(h - 1) + 8(h - 2) + ... + 2h ... (2)
从 (2) 中减去 (1),
S = h -2h + 2 + 4 + 8 + …。 + 2h
= -h – 1 + (1 + 2 + 4 + 8 +… + 2h )
= (2h + 1 - 1) – (h + 1)
[注:1 + 2 + 4 + 8 + ... + 2h = (2h + 1 - 1)
由于高度为 h 的完全二叉树具有 2h 到 2h + 1 个节点,因此上述总和为 O(n),其中 n 是堆中的节点数。
S = ∑0≤i≤h (h - i ) * 2i
S = h + 2(h - 1) + 4(h - 2) + ... + 2h - 1 ... (1)
Multiply both sides by 2,
2S = 2h + 4(h - 1) + 8(h - 2) + ... + 2h ... (2)
Subtract from (1) from (2),
S = h -2h + 2 + 4 + 8 + …. + 2h
= -h – 1 + (1 + 2 + 4 + 8 +… + 2h )
= (2h + 1 - 1) – (h + 1)
[Note: 1 + 2 + 4 + 8 + ... + 2h = (2h + 1 - 1)
Since a complete binary tree of height h has between 2h and 2h + 1 nodes, the above sum is O(n) where n is the number of nodes in the heap.
如果您不是从顶部开始计数,而是从底部开始计数,那么会更容易看出。因此,如果我们说
i
是距底部的高度,我们会将总和转换为:Σ i * 2hi
= 2h * Σ i / 2i
= 2h * O(1)
= O(2logn) = O(n)
我用 logn 交换了 h ,因为这是一个二进制文件堆。
我将证明为什么该和是 O(1):
该和是 i/2i 项的有限和,因此如果我们显示无限和的收敛性 (i-->infinite )那么显然每个有限和(即对于所有n)将小于该值(因为所有项都是正数)。这意味着每个有限和都受一个常数限制,即 O(1)。
我们只剩下无限 Σ i / 2i 收敛的证明。我们可以使用无数的收敛测试,让我们使用 Σ 1 / i2 收敛的简单结果,并表明对于足够大的 i ,这将是我们总和的上限:
我们想要证明,对于足够大的情况i:
i/2i 1/i2
发生当且仅当 i3 < 2i 这对于 i > 来说是正确的。 10
量子电动力学
It's a little easier to see if instead of your
i
running from the top, you count from the bottom. So if we sayi
is the height from the bottom we transform your sum into:∑ i * 2h-i
= 2h * ∑ i / 2i
= 2h * O(1)
= O(2logn) = O(n)
I swapped h with logn since this is a binary heap.
I'll justify why that sum is O(1):
The sum is a finite sum of the terms i/2i, so if we show convergence of the infinite sum (i-->infinite) then obviously every finite sum (i.e. for all n) will sum to less than that value (since all terms are positive). Meaning every finite sum is bounded by a constant, i.e. O(1).
We are left with just the proof that the infinite ∑ i / 2i converges. We can use a myriad of convergence tests, let's use the simple result that ∑ 1 / i2 converges and show that for large enough i that will upper bound our sum:
We want to show that for large enough i:
i/2i < 1/i2
which happens iff i3 < 2i which is true for, say, i > 10
QED