While reading a post on building a Binary Heap. I got confused in approach1.
The author's approach1(O(n*log n)):
Given a list of keys, build a binary heap by inserting each key one at a time.
Since you are starting with a list of one item, the list is sorted and you could use binary search to find the right position to insert the next key at a cost of approximately O(logn) operations.
However, inserting an item in the middle of the list may require O(n) operations to shift the rest of the list over to make room for the new key.
Therefore, to insert n keys into the heap would require a total of O(nlogn) operations.
`
class BinHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def percUp(self,i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.heapList[i] = tmp
i = i // 2
def insert(self, k):
self.heapList.append(k)
self.currentSize = self.currentSize + 1
self.percUp(self.currentSize)
I didn't understand why he needs to do Binary search to find the right position to insert the next when I can simply use the insert() on each key at a time and percUp() will take care of restoring the heap's property every time.Also, how my approch differs from his O(n*log n) approach:
def method1(list):
newHeap = BinHeap()
for key in list:
newHeap.insert(key)
return newHeap.heapList
list_keys= [9,6,5,2,3]
print('Method-1', method1(list_keys)[1:])
and get the result
Method-1 [2, 3, 6, 9, 5]
Please suggest where I am going wrong & what I am missing?