awelgorithms

Flip the compare to switch heap type

Updated

Keep the same parent/child index math. In sift up/down, min-heap swaps when the child is smaller; max-heap swaps when the child is larger. Or pass cmp.

What to focus on

Min: swap while a[i] < a[parent]. Max: swap while a[i] > a[parent]. Layout 2i+1 and floor((i-1)/2) does not change.

Worked examples

min insert

a = [1, 4, 9], insert 0, min cmp
  1. swap while child < parent
  2. 0 sifts to root

Result: [0, 1, 9, 4]

max insert

a = [9, 4, 1], insert 10, max cmp
  1. swap while child > parent
  2. 10 sifts to root

Result: [10, 9, 1, 4]

same code path

a = [7], insert 3
  1. one compare at parent 0
  2. min yields [3, 7]
  3. max yields [7, 3]

Result: type is the compare

Try it

Write siftUp(a, i, cmp). a is the heap. i is the new leaf. cmp(child, parent) returns true when they should swap, false otherwise. parent(i) = Math.floor((i-1)/2). Return a. Print min vs max after the named inserts. Min-heap [1, 4, 9] insert 0 → [0, 1, 9, 4] Max-heap [9, 4, 1] insert 10 → [10, 9, 1, 4] [7] insert 3 → min [3, 7], max [7, 3]

a is a non-empty heap of 1–6 integers. Min vs max is only the compare. cmp returns true or false. parent(i) = Math.floor((i-1)/2).