a Consider storing a heap as a linked binary tree with point
(a) Consider storing a heap as a linked binary tree with pointers. Give pseudocode on how you would store a heap node, and which modifications you need to make to the heap routines that we discussed in class. What are the runtimes of the heap routines?
(b) Now consider storing a heap as a linked list with pointers. Give pseudo-code on how you would store a heap node, and which modifications you need to make to the heap routines that we discussed in class. What are the runtimes of the heap routines?
(c) Which of the three heap implementations (array, linked tree, linked list) is preferrable? Justify your answer.
(d) Assume you are given two heaps of height h each, that are given as linked binary trees. And assume we do not require that the last level of the heap is “flushed left”, i.e., keys can be in any place in the last level. Give an efficient algorithm that merges those two heaps into one heap (without the “flushed left” condition). Analyze the runtime of your algorithm.
Solution
class BinaryHeap:
def _in(selfheap):
selfheap.heapListvalues = [0]
selfheap.currentSizevalue = 0
def percUpheap(selfheap,j):
while j // 2 > 0:
if selfheap.heapListvalues[i] < selfheap.heapListvalues[j // 2]:
tmprory = selfheap.heapListvalue[j // 2]
selfheap.heapListvalue[j // 2] = selfheap.heapListvalue[i]
selfheap.heapListvalue[i] = tmprory
j=j // 2
def insertheap(selfheap,k):
selfheap.heapListvalue.append(k)
selfheap.currentSize = selfheap.currentSize + 1
selfheap.percUpheap(selfheap.currentSize)
def percDownheap (selfheap,j):
while (j * 2) <= selfheap.currentSize:
nc = selfheap.minChild(j)
if selfheap.heapListvalue[j] > selfheap.heapListvalue[nc]:
tmprory = selfheap.heapListvalue[j]
selfheap.heapListvalue[j] = selfheap.heapListvalue[nc]
selfheap.heapListvalue[nc] = tmprory
j= nc
def minChild(selfheap,j):
if j* 2 + 1 > selfheap.currentSize:
return j * 2
else:
if selfheap.heapListvalueji*2] < selfheap.heapListvalue[j*2+1]:
return j * 2
else:
return j * 2 + 1
def deheaplMin(selfheap):
retval = selfheap.heapListvalue[1]
self. heapheapListvalue[1] = selfheap.heapListvalue[selfheap.currentSize]
selfheap.currentSize = self.currentSize - 1
selfheap.heapListvalue.pop()
selfheap.percDownheap (1)
return retval
def buildHeap(selfheap,alist):
j = len(alist) // 2
selfheap.currentSize = len(alist)
selfheap.heapListvalue= [0] + alist[:]
while (i > 0):
selfheap.percDownheap (j)
j = j - 1
bh = BinHeap()
bh.buildHeap([9,5,6,2,3])
print(bh.delMin())
print(bh.delMin())
print(bh.delMin())
print(bh.delMin())
print(bh.delMin())

