0

Below is my max heap implementation. I can really figure out why I am getting the index out of bounds error. I have assigned array to 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])

Error:

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
user1006915
  • 19
  • 1
  • 2

1 Answers1

1

You have this code:

    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]:

You're trying to index into the list before checking to see if the index is beyond the list's bounds. Besides, you want to check the index to see if it's within bounds, rather than checking that the contents at that index is within bounds.

It should be:

    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]:

It's unclear to me whether your root is at 0 or 1.

If the root node is at list[0], then your calculations should be (2*index) + 1 and (2*index)+2. The calculations you have assume that the root is at list[1].

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351