How do you know that when you bubble up a level, you won't have
to bubble it back down? If we have a parent p and 2 children: lc and
rc, where lc is what we're bubbling up, then the p-rc relationship
already obeys the heap property, so key(p) < key(rc). If we bubble
up lc, the key(lc) < key(p). Therefore key(lc) < key(rc), and we
will not need to bubble back down.
def parent(loc):
return loc // 2
def insertItem(heap, item, key):
# Insert at the end of the heap
heap.append((key, item))
# Get the location of the newly inserted item
loc = len(heap) - 1
# Bubble up the item if it is smaller than its parent
while loc != 0 and heap[parent(loc)][0] > key:
# Swap the item and its parent
heap[loc], heap[parent(loc)] = heap[parent(loc)], heap[loc]
# Move to the parent location
loc = parent(loc)