【问题标题】:Why is _siftup and _siftdown just the opposite in Python?为什么 _siftup 和 _siftdown 在 Python 中正好相反?
【发布时间】: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 模块的内部,因为它们名称中的下划线表示。

标签: python heap heapq


【解决方案1】:

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

请注意,本文使用 Floyd 的原始术语“siftup”来表示现在所谓的筛选down。

似乎不同的作者对什么是“向上”和“向下”有不同的参考。

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

【讨论】:

猜你喜欢
  • 2019-08-17
  • 2021-09-29
  • 2015-08-03
  • 2014-06-13
  • 1970-01-01
  • 2022-06-28
  • 1970-01-01
  • 2018-05-14
  • 2019-10-18
相关资源
最近更新 更多