You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
For every node, the value os the children are greater or equal to its value
All the levels are filled— from left to right
Min-heap: The minimum is always at the root of the tree
Max-heap: The maximum is always at the root of the tree
Operations:
Add (place at the bottom, and if the order is broken, rise up)
Serve (swap the root with the last item, remove last item, while order is broken, sink)
Implementations:
Binary tree of linked nodes (downside: required extra references to move up the tree, takes up extra memory)
Array (possible, due to complemetness of binary tree, and its more compact)
Python Implementation as Array
classHeap:
def__init__(self):
self.count=0self.array= [None]
def__len__(self):
returnself.count# best case: O(1), when item is smaller or equal to parent# worst case: O(logN), when item has to rise all the way to the topdefadd(self, item):
ifself.count+1<len(self.array):
self.array[self.count+1] =itemelse:
self.array.append(item)
self.count+=1self.rise(self.count)
defrise(self, k):
whilek>1andself.array[k] >self.array[k//2]:
self.swap(k, k//2)
k//=2defswap(self, i, j):
self.array[i], self.array[j] =self.array[j], self.array[i]
# best case: O(1), when item is larger or equal to largest children# worst case: O(log N), when the item sinks all the way to the bottomdefget_max(self):
assertself.count>0, "Heap is empty!"maximum=self.array[0]
self.swap(0, self.count)
self.sink(0)
returnmaximumdefsink(self, k):
while2*k<=self.count:
child=self.largest_child(k)
ifself.array[k] >=self.array[child]:
breakself.swap(child, k)
k=childdeflargest_child(self, k):
if2*k==self.countorself.array[2*k] >self.array[2*k+1]:
return2*kelse:
return2*k+1
Heap Sort
Complexity
Note
Worst Case:
O(n log n)
Because it has to iterate over the list for every item
Best Case:
O(n log n)
Because it has to iterate over the list for every item
Stability:
No
For each element in a list, add it to the heap
While heap is not empty, get max item and put it into a new list