Question: Show me the steps to solve ( C ) Implement the algorithm In [ 7 5 ] : class TopKHeap ( ) : # The
Show me the steps to solve C Implement the algorithm In : class TopKHeap:
# The constructor of the class to initialize an empty data structure
def self k:
self.k k
self.
self.H MinHeap
def sizeself:
return lenselfAselfHsize
def getjthelementself j:
assert self.k
assert self.size
return self.Aj
def satisfiesassertionsself:
# is self.A sorted
for i in rangelenself:
assert self.Ai self.Ai f'Array A fails to be sorted at position iselfAi self.Ai
# is self.H a heap check minheap property
self.Hsatisfiesassertions
# is every element of self.A less than or equal to each element of self.H
for in rangelenselfA:
assert self.Ai self.Hminelement f'Array element is larger than min heap e
# Function : insertintoA In :
lass to initialize an empty data structure
self.Hsize
j:
elf:
fA:
self.Ai f'Array A fails to be sorted at position iselfAi self.Ai
eck minheap property
tions
self.A less than or equal to each element of self.H
fA:
self.Hminelement f'Array element AiselfAi is larger than min heap element selfHminelement
n that inserts an element into
end of the array A
u just added at the very end of
per place so that the array A is sorted.
st element" jHat None if no element was displaced
t: def insertintoAself elt:
k self.k
print k k
assrtselfsize k
self.Aappendelt
j lenselfA
while j and self.Aj self.Aj:selfAj self.AjselfAj self.Aj
j j
returnCode to handle when self.size self.k is already provided
def insertself elt:
size self.sizeif size self.k:
self.insertintoAelt
returnyour code hereIn particular delete the jth element where j means the least element.def deletetopkself j:
k self.k
assert self.size k # we need not handle the case when size is less than or equal to
assert j
assert j self.k
Complete the implementation for maxheap data structure. First complete the implementation of MaxHeap. You can cut and paste relevant parts from
previous problems although we do not really recommend doing that. A better solution would have been to write a single implementation that could have
served as heap based on a flag.
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
