Skip to content
Push (Sift-Up)
step 1/5

Reading — step 1 of 5

Read

~1 min readOperations

Push (Sift-Up)

Insertion: append at end, then bubble up while smaller than parent.

python

The new element starts at the bottom; if it's smaller than its parent, swap; repeat. At most log_2(n) swaps (height of the tree).

Why does this preserve the heap property? Before insert, all parent-child relationships are valid. The new element only violates with its parent. If it's smaller, swap puts smaller above; new violation could be with the GRANDPARENT (which was smaller than the parent's old value, but possibly bigger than the new one). Repeat.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…