Max heap throwing index out of bounds
<p>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</p>

<pre><code>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]&lt;=self.heapsize and list[2*index]&gt;list[index]:
            largest=list[2*index]
        else:
            largest=index
        if list[2*index+1]&lt;= self.heapsize and list[2*index+1]&gt;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])
</code></pre>

<p>Error:</p>

<pre><code>Traceback (most recent call last):
  File "heap.py", line 24, in &lt;module&gt;
    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]&lt;=self.heapsize and list[2*index]&gt;list[index]:
IndexError: list index out of range
</code></pre>

<p>You have this code:</p>

<pre><code>    if list[2*index]&lt;=self.heapsize and list[2*index]&gt;list[index]:
        largest=list[2*index]
    else:
        largest=index
    if list[2*index+1]&lt;= self.heapsize and list[2*index+1]&gt;list[index]:
</code></pre>

<p>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.</p>

<p>It should be:</p>

<pre><code>    if 2*index&lt;=self.heapsize and list[2*index]&gt;list[index]:
        largest=list[2*index]
    else:
        largest=index
    if 2*index+1&lt;= self.heapsize and list[2*index+1]&gt;list[index]:
</code></pre>

<p>It's unclear to me whether your root is at 0 or 1.</p>

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

python algorithm tree heap binary-heap