I wrote this insertion function for a max-heap:
def insertinmaxheap(arryhp, num):
arryhp.append(num)
arryhp.insert(0, 0)
l = len(arryhp) - 1
b = True
while b:
print(arryhp)
print(l)
print(int(l/2))
if num <= arryhp[int(l / 2)] or int(l/2) < 2:
b = False
arryhp[l] = arryhp[int(l/2)]
arryhp[int(l/2)] = num
l = int(l/2)
return arryhp[1:len(arryhp)]
I've tested it fore some values and it worked most of the time, but for this example it failed:
insertinmaxheap([50, 30, 20, 15, 10, 8, 16], 19)
The output is [50, 19, 20, 30, 10, 8, 16, 15], and as you can see 19 shouldn't be there.
What is wrong with this code?