【发布时间】:2014-05-30 14:48:00
【问题描述】:
我正在编写一个 O(n) 算法,用于在 Python 中“堆积”一个列表。我不明白为什么它不起作用。
def func(l):
size=len(l)
for root in range((size//2)-1,-1,-1):
child = 2*root+1 #parent of child is target
while(child<size):
#l[child] should be smaller sibling
if child<size-1 and l[child]>l[child+1]:
child+=1
#can we put l[root] in l[child//2]?
if l[root]<=l[child]:
break #yes
#no
l[child//2]=l[child]#move child up
child=2*child+1#move down a level
l[child//2]=l[root]
return l
【问题讨论】:
-
root 的子节点是否应该在 pos. 2*root 和 2*root+1?
-
@MicahSmith:如果索引是从零开始的,则不会,就像在 Python 中一样。
root的孩子是2*root+1和2*root+2。 -
@Blckknght 听起来不错。在我的 DS 课程中,我们学会了将 root 放入索引 1 并将索引 0 留空。 (在 heapify 期间既允许上面的模式并用作占位符。)
标签: python algorithm heap bottom-up