The Merge Process

  • Explain and trace the merge sort algorithm on a particular data sequence.

Consider the following two sorted list of numbers, A={1,3,5}A = \{1, 3, 5 \} and B={0,2,4,8,9}B = \{0, 2, 4, 8, 9 \}. We are interested in combining (merging) these two lists, such that the resulting merged list remains sorted.

Here is the naive approach:

StepDetailsRuntime
IMake a list, CC, large enough to hold all elements of AA & BBO(1)\Omicron(1)^{*}
IICopy elements of AA to CCO(n)\Omicron(n)
IIICopy elements of BB to CCO(m)\Omicron(m)
VISort CCO(sort)\Omicron(\text{sort})^{**}

^{*} O(m+n)\Omicron(m+n) depending on the language/data structure cost to construct the auxiliary space.
^{**} The O(sort)\Omicron(\text{sort}) will be linearithmic at best (for comparison-based sorting).

This solution does not make any use of the knowledge the two inputs were sorted, to begin with. So naturally, the question is: can we do better? And the answer is yes; with a bit of creativity, we can copy the numbers in AA and BB to CC, one at a time, and keep them in sorted order.

Linear-time merge