Useful to find the min and max values of a set of values. Are arrays under the hood
import heapq
minHeap = []
heapq.heappush(minHeap, 3)
# Min is always at index 0
# To do heapsort
while len(minHeap):
print(heapq.heappop(minHeap))Max Heaps in Python
By default does not exist in python, but we can multiply the value we push into it by -1 and when we pop out of it we multiply by -1 as well
import heapq
maxHeap = []
heapq.heappush(maxHeap, -3)
heapq.heappush(maxHeap, -4)
heapq.heappush(maxHeap, -2)
# Max is always at index 0
print(-1 * maxHeap[0])
while len(maxHeap):
print(-1 * heapq.heappop(maxHeap))Heapify
We can build a heap from an array in linear time O(n)
import heapq
arr = [2, 1, 8, 4, 5]
heapq.heapify(arr)