Question: Use the code provided to complete the problem in the picture using python with comments: class MinHeap: def _ _ init _ _ ( self

Use the code provided to complete the problem in the picture using python with comments:
class MinHeap:
def __init__(self):
self.data =[] # This list contains the heap elements
# The __str__ method simply returns the elements of the heap, in list form
def __str__(self):
return str(self.data)
# Adds a new element to the heap
def add(self, new_data):
# First add the element to the end of the list (maintains the complete
# tree property)
self.data.append(new_data)
# Index of the last list element
index = len(self.data)-1
# Do the "percolate up" process - swap the new node with its parent as
# many times as needed to maintain the min-heap property
while index >0: # Loop exits once we reach the root (index 0)
# Compare this element vs. its parent
parent_index =(index -1)//2
# If the parent is larger than the child...
if self.data[parent_index]> self.data[index]:
# Swap the parent with the child
self.data[parent_index], self.data[index]= self.data[index], self.data[parent_index]
# Update the current index
index = parent_index
# If the parent is *not* larger than the child, the min-heap
# property isn't violated and we can stop
else:
break
Use the code provided to complete the problem in

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!