堆数据结构

发布于 2024-08-26 20:05:57 字数 78 浏览 11 评论 0原文

尝试考虑最大堆中第 n 个最大键的位置的下限。假设堆按数组排列。我认为上限是 min(2^n-2, 数组大小 -1),但它的下限总是 0 吗?

Trying to think of a lower bound to the position of say, the nth largest key in a max-heap. Assuming the heap's laid out in array. The upper bound's min(2^n-2, array size -1) i think, but is it always lower bounded by 0?

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

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

发布评论

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

评论(1

云归处 2024-09-02 20:05:57

对问题的初步调查揭示了 n 与下限和上限之间的以下关系(假设堆中有 14 个元素)

n   lb  up
1   1   1
2   2   3
3   2   7
4   2   14
9   3   14
10  4   14
12  5   14
13  6   14
14  8   14

要确定可能大于堆数组特定位置中的元素的元素数,请计算以该位置为根的子树的大小。然后,这两个数字通过公式编辑相关

# of elements possible larger  = total number of elements - size of subtree - 1 


请注意,计算是向后执行的。给定数组/堆中的位置,如果堆已排序,则可以确定该值将位于哪个位置。给定节点,堆可以分为三个分区:

  1. 保证大于当前元素的元素(父元素、父元素、...)
  2. 保证小于当前元素的元素(以子树为根的子树)在当前元素处)
  3. 剩余的元素可以大于或小于当前元素。

如果我们查看一个包含 14 个元素的示例堆,并想要确定第 6 个位置中可能值的范围,则组如下: 第

  • 1 组包含两个元素 (3, 1)
  • 第 2 组包含两个元素 (12, 13)
  • 第 3 组包含剩余的 9 个元素(不包括当前值)(2, 4, 5, 7, 8, 9, 10, 11, 14),

因此下限为 3(第 1 组中的元素数量 + 1),而上限为 11(第一组中的元素数量 + 第三组中的元素数量 + 1)。

Initial investigation of the problem reveals the following relation between n and the lower and upper bounds (assumption there are 14 elements in the heap)

n   lb  up
1   1   1
2   2   3
3   2   7
4   2   14
9   3   14
10  4   14
12  5   14
13  6   14
14  8   14

To determine the number of elements that are possible larger than the element in a specific location of the heap array, calculate the size of the subtree rooted at that location. These two numbers are then related by the formula

# of elements possible larger  = total number of elements - size of subtree - 1 

EDIT:
Note that the calculation is performed backwards. Given a position in the array / heap, it is possible to determine in which position the value will be if the heap were sorted. Given the node the heap can be divided into three partitions:

  1. Elements that are guaranteed to be larger than the current element (the parent, the parents parent, ...)
  2. Elements that are guaranteed to be smaller than the current element (the subtree rooted at the current element)
  3. The remaining elements which can be either larger or smaller than the current element.

If we look at an example heap with 14 elements and want to determine the range of possible values in the 6th location, the groups are as follows:

  • Group 1 contains two elements (3, 1)
  • Group 2 contains two elements (12, 13)
  • Group 3 contains the remaining nine elements (excluding the current value) (2, 4, 5, 7, 8, 9, 10, 11, 14)

The lower bound is therefore 3 (# of elements in group one + 1) while the upper bound is 11 (# of elements in group one + # of elements in group three + 1).

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