I am learning data structures and my code is not working properly..I tried dubugging and couldn't found anything(seems like heapifyinsert() is not doing anything)
Here is my code:
class Heap:
def __init__(self,size):
self.heap=[None]*(size+1)
self.heapsize=0
self.maxheapsize=size+1
def levelordertransversal(self):
if not self.heap:
raise Exception('Heap doesn\'t exists')
for x in range(1,self.heapsize+1):
print(self.heap[x])
def heapifyinsert(self,index,heaptype):
heaptype=heaptype.title()
parentindex=int(index/2)
if parentindex<=1:
return
if heaptype=='Min':
if self.heap[index]<self.heap[parentindex]:
temp=self.heap[index]
self.heap[index]=self.heap[parentindex]
self.heap[parentindex]=temp
self.heapifyinsert(parentindex,heaptype)
elif heaptype=='Max':
if self.heap[index]>self.heap[parentindex]:
temp=self.heap[index]
self.heap[index]=self.heap[parentindex]
self.heap[parentindex]=temp
self.heapifyinsert(parentindex,heaptype)
def insertnode(self,nodevalue,heaptype):
if self.heapsize+1==self.maxheapsize:
raise Exception('Heap is full!!')
self.heap[self.heapsize+1]=nodevalue
self.heapsize+=1
self.heapifyinsert(self.heapsize,heaptype)
h=Heap(5)
h.insertnode(4,'Max')
h.insertnode(5,'Max')
h.insertnode(2,'Max')
h.insertnode(1,'Max')
h.levelordertransversal()
Current output:
4
5
2
1
Expected output:
5
4
2
1
So here in the above code I tried to implement heap starting with index position 1(for the sake of simplicity) and in heapifyinsert() method we are taking parentindex and checking if the value at parent index is greater or less according to heap type and swapping the values
Any help or clue will be appreciated..Thanks!
heaptype=heaptype.title()? This instruction alters the value of heaptype provided as a variable to the function.