gpt4 book ai didi

python - 为什么 _siftup 和 _siftdown 在 Python 中正好相反?

转载 作者:行者123 更新时间:2023-12-04 13:19:34 25 4
gpt4 key购买 nike

来自binary heap的定义在维基百科中,sift-up 也称为 up-heap 操作,sift-down 称为 down-heap

所以在堆(完全二叉树)中,up表示从叶到根,down表示从根到叶。

但是在python中,似乎恰恰相反。我对 siftupsiftdown 的含义感到困惑,并且在我第一次使用时被误用。

这里是heapq_siftdown_siftup的python版本实现:

# 'heap' is a heap at all indices >= startpos, except possibly for pos.  pos
# is the index of a leaf with a possibly out-of-order value. Restore the
# heap invariant.
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if newitem < parent:
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem

def _siftup(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2*pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not heap[childpos] < heap[rightpos]:
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2*pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)

为什么在python中相反?我已经在 wiki 和其他几篇文章中确认过。有什么我遗漏或误解的吗?

感谢阅读,非常感谢它能帮助我。 :)

最佳答案

查看维基百科页面上的引用资料,我发现了这一点:

Note that this paper uses Floyd's original terminology "siftup" for what is now called sifting down.

似乎不同的作者对什么是“上”和“下”有不同的引用。

但是,正如@Dan D 在评论中所写,无论如何您都不应该使用这些函数。

关于python - 为什么 _siftup 和 _siftdown 在 Python 中正好相反?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55375312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com