50 XP

20. Merge two sorted lists

Intermediate lists two pointers

Write a function merge(a, b) that takes two lists of numbers, each already sorted from smallest to largest, and returns one new list with all the items of both, also sorted from smallest to largest.

Don't call sorted() or .sort(). Both lists are already in order, so you can walk through them side by side and always take the smaller of their front items.

Keep every item, repeats included: a number that is in both lists appears twice in the result. Either list, or both, can be empty.

Example 1

Inputa = [1, 4, 9], b = [2, 3, 10]
Output[1, 2, 3, 4, 9, 10]
ExplanationThe items of both lists, smallest first.

Example 2

Inputa = [], b = [5, 6]
Output[5, 6]
Explanationa is empty, so the result is just b.

Example 3

Inputa = [2, 2], b = [1, 2]
Output[1, 2, 2, 2]
ExplanationEvery 2 is kept, from both lists.

Constraints

  • a and b each have 0 to 50 whole numbers.
  • Each list is sorted from smallest to largest, and can hold repeats.

Submit also runs 4 more tests you can't see.

Practises While Loops (lesson 14).

Code
def merge(a, b):
    """Merge two sorted lists into one sorted list.

    a, b: list of int, each sorted smallest first;
        either may be empty
    Returns: list of int, all their items, sorted, made
        without sorted() or .sort()
    """
    # Write your code here
    pass