下面是我的最大堆实现。我真的可以弄清楚为什么我得到索引越界错误。我已将数组分配给self.heap
Imports Microsoft.Office.Core
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
' Start Excel and get Application object.
oXL = CreateObject("Excel.Application")
oXL.Visible = True
End Sub
End Class
错误:
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])
答案 0 :(得分:1)
您有以下代码:
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]:
在检查索引是否超出列表边界之前,您尝试索引到列表中。此外,您要检查索引是否在边界内,而不是检查该索引的内容是否在边界内。
应该是:
if 2*index<=self.heapsize and list[2*index]>list[index]:
largest=list[2*index]
else:
largest=index
if 2*index+1<= self.heapsize and list[2*index+1]>list[index]:
我不清楚你的根是0还是1。
如果根节点位于list[0]
,则您的计算应为(2*index) + 1
和(2*index)+2
。您的计算假设根位于list[1]
。