I’ve been asked to come up with as many solutions as possible to the following problem:
Write a function which takes two lists of numbers (both assumed to
be in ascending order) and merges them into a single list (also in
ascending order).
My first solutions was to append list1 onto list2 and then re-sort.
Then I found a built-in merge.
Then I decided to actually implement a solution myself, and I came up with a tail recursive function that, at the moment, only works for a subset of lists.
The problem itself seems like maybe I finally have a reason to read Knuth, but alas Uni and the Library are closed due to snow.
So I turn to you SO, what are some interesting, or efficient, or anti-pattern approaches to this problem?
P.S I’m not looking for implementations, unless thats the best way to demonstrate the idea. I’m just looking to see how people have approached this type of problem.
Merging two sorted lists is algorithmically trivial.
Start with the first element of each list, compare, write the lower one to output and advance the list where you found the lower one. Keep going until you reach the end of one list, then put out the remainder of the other list.
This requires just one loop over each list and max. one comparison per output element.
Edit: This is as efficient as it gets for two lists. It gets (a little bit) trickier when you have a large number of lists to merge.