Question: class MinHeap: def _ _ init _ _ ( self ) : self.H = [ None ] def size ( self ) : return len
class MinHeap:
def initself:
self.H None
def sizeself:
return lenselfH
def reprself:
return strselfH:
def satisfiesassertionsself:
for i in range lenselfH:
assert self.Hi self.Hi f'Min heap property fails at position i parent elt: selfHi child elt: selfHi
def minelementself:
return self.H
## bubbleup function at index
## WARNING: this function has been cut and paste for the next problem as well
def bubbleupself index:
assert index
if index :
return
parentindex index
if self.Hparentindex self.Hindex:
return
else:
self.Hparentindex self.Hindex self.Hindex self.Hparentindex
self.bubbleupparentindex
## bubbledown function at index
## WARNING: this function has been cut and paste for the next problem as well
def bubbledownself index:
assert index and index lenselfH
lchildindex index
rchildindex index
# set up the value of left child to the element at that index if valid, or else make it Infinity
lchildvalue self.Hlchildindex if lchildindex lenselfH else floatinf
# set up the value of right child to the element at that index if valid, or else make it Infinity
rchildvalue self.Hrchildindex if rchildindex lenselfH else floatinf
# If the value at the index is lessthan or equal to the minimum of two children, then nothing else to do
if self.Hindex minlchildvalue, rchildvalue:
return
# Otherwise, find the index and value of the smaller of the two children.
# A useful python trick is to compare
minchildvalue, minchildindex min lchildvalue, lchildindexrchildvalue, rchildindex
# Swap the current index with the least of its two children
self.Hindex self.Hminchildindex self.Hminchildindex self.Hindex
# Bubble down on the minimum child index
self.bubbledownminchildindex
# Function: heapinsert
# Insert elt into heap
# Use bubbleupbubbledown function
def insertself elt:
# your code here
self.Happendelt
self.bubbleuplenselfH
# Function: heapdeletemin
# delete the smallest element in the heap. Use bubbleupbubbledown
def deleteminself:
# your code here
if lenselfH:
return None
# Save the minimum value to return it later
minval self.H
# Replace the root with the last element in the heap
self.H self.H
# Remove the last element
self.Hpop
# Restore the heap property by bubbling down the root element
self.bubbledown
return minval
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
