堆排序“Heapify”迭代过程

发布于 2025-01-16 04:23:27 字数 676 浏览 3 评论 0原文

我正在检查 max-heapify 算法的迭代方法,以下是 CLRS 解决方案中给出的内容。

while i < A.heap-size do
l =LEFT(i)
r =LEFT(i)
largest = i
if l ≤ A.heap-size and A[l] > A[i] then
largest = l
end if
if r ≤ A.heap-size and A[r] > A[i] then
largest = r
end if
if largest not equal i then
exchange A[i] and A[largest]
i = largest
else return A
end if
end while
return A

我的问题是为什么循环条件给出为 i i i i i i i i i i i i < A.堆大小?由于左右应该在堆大小之内,这意味着父级必须是i <= A.heap-size/2,为什么我们不能检查这样的条件<代码>i<=A.heap-size/2

I was checking the iterative approach for the max-heapify algorithm and the following is what is given in CLRS solutions.

while i < A.heap-size do
l =LEFT(i)
r =LEFT(i)
largest = i
if l ≤ A.heap-size and A[l] > A[i] then
largest = l
end if
if r ≤ A.heap-size and A[r] > A[i] then
largest = r
end if
if largest not equal i then
exchange A[i] and A[largest]
i = largest
else return A
end if
end while
return A

My question is why the loop condition is given as i < A.heap-size? Since the left and right should be within the heap size, which would mean that the parent must be i <= A.heap-size/2, why can't we check the condition as such i<=A.heap-size/2?

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

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

发布评论

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

评论(1

各空 2025-01-23 04:23:27

是的,你是对的,检查到堆大小/2 就足够了。之后我们甚至没有这些节点的子节点。

Yeah you are correct , it is just sufficient to check till heap-size/2. After that we don't even have children for those nodes.

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