Merging Two Sorted Sequences

Merging selects the smaller current head from two sorted sources until both sources are exhausted.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Walk the heads
  2. Choose the tie rule
  3. Trace a tie that reveals stability
  4. Check both exhaustion directions

Walk the heads

From 2, 7 and 3, 5, take 2, then 3, then 5, then append 7. At each choice the smaller head cannot be larger than any unvisited entry within either source. This is the combine step in a common divide-and-conquer sort.

Choose the tie rule

Taking from the left source first when keys tie preserves original ordering for halves of one sequence. Stable ordering explains why this matters when records have names as well as sortable scores.[1]

Trace a tie that reveals stability

Let left contain (1, A), (4, B) and right contain (1, C), (3, D). When the primary keys agree, take the item from the left run first for stability across these two contiguous original runs. Remember that the untouched tail is already internally ordered. See stable ordering in practice.

Compare 1 and 1: emit A
Compare 4 and 1: emit C
Compare 4 and 3: emit D
Right exhausted: append B
Output: A, C, D, B

Check both exhaustion directions

A merge should copy the rest of the right range when the left ends first, and the rest of the left when the right ends first. An empty run lets you test each rule without any comparison. Verify presortedness as a precondition when callers can provide arbitrary inputs.

References

  1. Jeff Erickson, Algorithms ↩