Почему _siftup и _siftdown в Python противоположны?
Из определения двоичной кучи в Википедии, sift-up
также называется up-heap
операция и sift-down
называется down-heap
,
Итак, в куче (полное двоичное дерево), up
означает от листа до корня, и down
означает от корня до листа.
Но в питоне это выглядит как раз наоборот. Я смущен смыслом siftup
а также siftdown
и неправильно, когда мой первый раз.
Вот реализация Python версии _siftdown
а также _siftup
в 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)
Почему наоборот в питоне? Я подтвердил в вики и нескольких других статьях. Есть ли что-то, что я пропустил или недоразумение?
Спасибо за чтение, я действительно ценю это, чтобы выручить меня.:)
1 ответ
Глядя на ссылки на странице Википедии, я заметил это:
Обратите внимание, что эта статья использует оригинальную терминологию Флойда "siftup" для того, что сейчас называется "отсеивание".
Казалось бы, разные авторы имеют разные ссылки на то, что "вверх" и "вниз".
Но, как пишет @Dan D в комментарии, вы все равно не должны использовать эти функции.