How does upheap restore the heap-order property after an insertion, and how long does it take?
Upheap repeatedly swaps the new key k with its parent's key as long as the parent's key is larger, stopping when the parent is not larger or k has reached the root. It follows one path upwards, so it takes $O(\log n)$.
* Key 1 enters at the next free slot and climbs one level per swap until no parent is larger. *
After an insertion, the only place where the heap order can be broken is between the new node and its parent: everything else was a valid heap before. Upheap fixes that one spot and checks whether the fix created a new problem one level up:
upheap(z):
while z is not the root and key(parent(z)) > key(z):
swap the entries of z and parent(z)
z ← parent(z)
Example: insert 1 below 6 in the heap 2 → (5, 6), 5 → (9, 7).
- 1 < 6: swap. 1 now sits where 6 was, 6 moves down into the new node.
- 1 < 2: swap. 1 becomes the root.
- At the root: stop. The heap is 1 → (5, 2), 5 → (9, 7), 2 → (6).
Each swap is safe for the rest of the tree: the key that moves down (6, then 2) was already ≤ everything below it, so the subtrees stay valid.
Running time: at most one swap per level, and the heap has height $O(\log n)$, so upheap, and with it insert, costs $O(\log n)$. That is the worst case, when the new key is the new minimum: about 20 swaps in a heap of a million entries. In the best case the new key is already ≥ its parent (inserting 10 below the 6, say) and no swap is needed at all.
Go deeper:
Heap visualization (USFCA) — insert your own keys and watch every upheap swap, tree and array side by side.