I'm trying to animate a max heap tree step by step, however, I am struggling to store the intermediate steps in between in a list. When I run my code, it overlaps each of the values in the list with the final answer.
nums = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
def max_heapify(nums, index=0):
left = 2*index + 1
right = 2*index + 2
if left <= len(nums) - 1 and nums[left] > nums[index]:
largest = left
else:
largest = index
if right < len(nums) - 1 and nums[right] > nums[largest]:
largest = right
if largest != index:
nums[index], nums[largest] = nums[largest], nums[index]
max_heapify(nums, largest)
def build_max_heap(nums):
frame_list = []
for i in range(((len(nums)//2) - 1), -1, -1):
frame_list.append(nums)
max_heapify(nums, i)
return (frame_list)
build_max_heap(nums)
Returns:
[[16, 14, 10, 8, 7, 9, 3, 2, 4, 1],
[16, 14, 10, 8, 7, 9, 3, 2, 4, 1],
[16, 14, 10, 8, 7, 9, 3, 2, 4, 1],
[16, 14, 10, 8, 7, 9, 3, 2, 4, 1],
[16, 14, 10, 8, 7, 9, 3, 2, 4, 1]]