awelgorithms

Insert into a heap

Updated

Append x at a[size], size++, then sift up from the new index. The old root stays until the new value beats it on the path.

What to focus on

Insert does not write a[0] first. The new item starts as the last leaf. Insert 0 into [1, 4, 9] sifts to the root. parent(i) = Math.floor((i-1)/2).

Worked examples

sift to root

a = [1, 4, 9], insert 0
  1. append → [1, 4, 9, 0]
  2. i=3 parent 1: 0<4 swap
  3. i=1 parent 0: 0<1 swap

Result: [0, 1, 9, 4]

stay a leaf

a = [1, 4, 9], insert 7
  1. append → [1, 4, 9, 7]
  2. i=3 parent 1: 7>=4 stop

Result: [1, 4, 9, 7]

onto one

a = [7], insert 1
  1. append → [7, 1]
  2. i=1 parent 0: 1<7 swap

Result: [1, 7]

Try it

Write insert(a, x). a is a tight min-heap. x is the new value. Append at a[size], then sift up using parent(i) = Math.floor((i-1)/2). Return the heap. Print a after each swap. Insert 0 into [1, 4, 9] → [0, 1, 9, 4] Insert 7 into [1, 4, 9] → [1, 4, 9, 7] Insert 1 into [7] → [1, 7]

a is a non-empty tight min-heap of 1–6 integers. x is an integer. parent(i) = Math.floor((i-1)/2).