I am trying to implement a function that turns a list into a MinHeap. I cannot see where I am going wrong.
def min_heapify(nums):
n = len(nums) - 1
i = n // 2 # last parent
while i >= 1:
k = i
v = nums[k]
min_heap = False
while not min_heap and 2 * k <= n:
j = 2 * k
if j + 1 <= n:
if nums[j + 1] < nums[j]:
j += 1
if nums[k] < nums[j]:
min_heap = True
else:
nums[k] = nums[j]
k = j
nums[k] = v
i -= 1
Example Input:
a_list = [0, 5, 2, 3, 4]
min_heapify(a_list)
Output (the 4 is incorrect):
print("Min Heapify", a_list) # Min Heapify [0, 2, 5, 3, 4]
if nums[k] < nums[j]toif v < nums[j]. If you do that, there's no need to swapnums[j]andnums[k]as suggested in the accepted answer.