【发布时间】:2019-08-17 21:48:19
【问题描述】:
根据维基百科中binary heap的定义,
sift-up也叫up-heap操作,sift-down叫down-heap。
所以在堆(完全二叉树)中,up 表示从叶到根,down 表示从根到叶。
但在 python 中,它似乎正好相反。我对siftup 和siftdown 的含义感到困惑,并在我第一次使用时被误用。
这里是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 和其他几篇文章中确认过。有什么我遗漏或误解的吗?
感谢您的阅读,非常感谢它帮助我。 :)
【问题讨论】:
-
您不应该直接使用其中任何一个。它们是 heapq 模块的内部,因为它们名称中的下划线表示。