I have implemented min-heap in python, but after some tests I realized that sometimes approximately after every 10th insert it puts it in the wrong position(the parent is larger than child). The code:
class minHeap():
def __init__(self):
self.heap = [] # main array
def get_parent(self, i):
return i//2
def bubble_up(self):
i = len(self.heap)-1
p = self.get_parent(i)
while self.heap[p] > self.heap[i]:
self.heap[i], self.heap[p] = self.heap[p], self.heap[i] # swapping parent and child
i = p
p = self.get_parent(i)
def insert(self, k):
self.heap.append(k)
self.bubble_up()
My last 2 hours has been spent searching for the bug, so I would really appreciate if someone would help me.