A heap always knows the smallest item
Some questions keep asking one thing of a collection that keeps changing: which item is the smallest right now? The credit that expires soonest. The meeting that ends first. The farthest of the points you've kept. The nearest server you haven't reached yet.
A heap answers that question quickly. This lesson builds one from a plain list, uses it in three patterns, and ends back at the GPU credit ledger.
Look at the smallest in O(1), push or pop in O(log n)
Here's what a heap promises, with n the number of items it holds:
- Look at the smallest: O(1). It's always
heap[0]. - Push an item, or pop the smallest: O(log n).
- Turn a list of n items into a heap: O(n).
Test that against the two things you'd try first: scan for the smallest each time, or keep the list sorted. Each step below pops the smallest item and pushes a new one, on a list of n random floats.
# unsorted list: find the smallest every time
def scan(a, new):
for x in new:
a.remove(min(a))
a.append(x)
# sorted list, sorted again after each push
def sort_every_time(a, new):
for x in new:
a.pop(0)
a.append(x)
a.sort()
# sorted list, each new item inserted in place
def keep_sorted(a, new):
for x in new:
a.pop(0)
bisect.insort(a, x)
# a heap, with heapq
def heap(a, new):
for x in new:
heapq.heappop(a)
heapq.heappush(a, x)
One pop and one push on a heap of 1,000 took 0.17 µs. About how long on a heap of 100,000?