Back to Challenge Set 20

Code Challenge: Merge

Difficulty  

divider

The Brief

What they asked for
Two of my machines each keep their own sorted list of job
numbers. I want one combined list, still sorted, and I do not
want you to just glue them together and sort the result. That
is wasteful and I will be able to tell.

Write your requirements list before you write any code. Input, calculate, output, and anything you had to decide for yourself.


Notes

  • Both inputs are already sorted. That is worth something, and the brief is telling you to use it.
  • Walk both arrays at once, with a separate position in each. Take whichever front value is smaller, then move on in that array only.
  • One array runs out before the other. Deal with the leftovers.
  • Duplicates across the two arrays are allowed. Keep both.
  • The merged array is new int[a.Length + b.Length]: its size is known before you start. Count your steps and compare the count with that length.

Sample Output

Sample Output
Merged: 1 3 9 9 14 15 22 30 41
Steps: 9 (a has 4, b has 5)

Nine steps for nine numbers: every number is placed exactly once. Gluing and then selection-sorting would cost 36 comparisons.


Submit

Your requirements list and your program file, named cc-merge-lists.

Commence Challenge