0
下面是我的最大堆實現。我可以真正弄清楚爲什麼我得到索引超出界限的錯誤。我已經指定數組self.heap最大堆投擲指數越界
class heap:
def __init__(self):
self.heapsize=0
self.heap=[0]
def builheap(self,list):
self.heapsize = len(list)
self.heap=list
for i in range(len(list)//2, 0, -1):
self.maxheap(self.heap,i)
def maxheap(self, list, index):
if list[2*index]<=self.heapsize and list[2*index]>list[index]:
largest=list[2*index]
else:
largest=index
if list[2*index+1]<= self.heapsize and list[2*index+1]>list[index]:
largest=list[2*index+1]
if largest!=index:
tmp = list[index]
list[index] = list[largest]
list[largest] = tmp
maxheap(list,largest)
h=heap()
h.builheap([16,14,10,8,7,9,3,2,4,1])
錯誤:
Traceback (most recent call last):
File "heap.py", line 24, in <module>
h.builheap([16,14,10,8,7,9,3,2,4,1])
File "heap.py", line 9, in builheap
self.maxheap(self.heap,i)
File "heap.py", line 11, in maxheap
if list[2*index]<=self.heapsize and list[2*index]>list[index]:
IndexError: list index out of range