<p>我正在尝试用Python实现堆排序算法。
我得到了一个错误:list index out of range,尽管如果索引超出范围,那么这部分代码不应该执行。在</p>
<pre><code>def swaper(child,parent,a):
temp = a[parent]
a[parent]=a[child]
a[child]=temp
def digswap(swap,a):
'''
swap here is the position of the former child, which was just swapped with
its parent. The concept is to check if the node that now contains the parent value
has childs. If it has, then we might have to restore the heap property.
'''
if (2*swap)<=len(a):
if a[2*swap]>a[swap]:
swaper(2*swap, swap, a)
digswap(2*swap,a)
if (2*swap+1)<=len(a):
if a[2*swap+1]>a[swap]:
swaper(2*swap+1, swap, a)
digswap(2*swap+1,a)
</code></pre>
<p>我得到“if a[2*swap]>;a[swap]”的“list index out of range value”(列表索引超出范围值)。我不明白为什么,因为如果2*swap>;lean(a),这个部分不应该执行。在</p>