awelgorithms

Drain until the merge heap is empty

Updated

While the heap is nonempty: pop the smallest head, emit it, push that sequence's next if any. Stop when size == 0. The emit list is the merge.

What to focus on

Empty heap means every sequence is exhausted. Do not stop while a leftover head remains. a = [1, 4, 9], b = [4, 7] emits 1,4,4,7,9.

Worked examples

full merge

a = [1, 4, 9], b = [4, 7]
  1. pop 1 push 4_a
  2. pop 4 push 9_a or 7_b
  3. continue until empty

Result: 1, 4, 4, 7, 9

a only leftover

a = [1, 4, 9], b = [4]
  1. after both 4s, drain 9 from a

Result: 1, 4, 4, 9

b shorter

a = [1], b = [4, 7]
  1. pop 1, a done
  2. pop 4 push 7
  3. pop 7

Result: 1, 4, 7

Try it

Write drain(a, b). a and b are non-decreasing sequences. The heap holds one head per nonempty sequence. Pop with extract, push with insert. Return the merged list. Loop while the heap is nonempty. Print the emit list. [1, 4, 9] with [4, 7] → 1, 4, 4, 7, 9 [1, 4, 9] with [4] → 1, 4, 4, 9 [1] with [4, 7] → 1, 4, 7

a and b are non-decreasing sequences of 1–4 integers. Stop when the heap is empty because every sequence is exhausted.