从维基百科
二叉堆的定义来看,sift-up也称为up-heap操作,sift-down称为down-heap。
所以在堆(完全二叉树)中,up表示从叶到根,down表示从根到叶。
但在Python中,情况似乎恰恰相反。siftup我对and的含义感到困惑siftdown,并且在第一次使用时被误用。
_siftdown以下是和_siftup中的 python 版本实现heapq:
# '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)
Run Code Online (Sandbox Code Playgroud)
为什么在Python中相反?我已经在 wiki 和其他几篇文章中确认了。我有什么遗漏或误解吗?
感谢您的阅读,我真的很感谢它对我的帮助。:)
查看维基百科页面上的参考资料,我发现了这一点:
请注意,本文使用弗洛伊德最初的术语“siftup”来表示现在所谓的“sifting down”。
似乎不同的作者对“上”和“下”有不同的参考。
但是,正如@Dan D 在评论中所写,无论如何你都不应该使用这些函数。