DSA Factory
Free Sorting lessonsSorting · Stage 2 · Merge sort and counting · Step 1

Zip two sorted lists together

Merge two sorted lists into one sorted list by always taking the smaller of the two front values. About 12 minutes.

Compare the fronts

Keep a finger on the front of each list. Compare the two values your fingers point at. The smaller one is the smallest of everything that's left, so write it down and move that finger forward one place.

Keep going until one list runs out. Then the other list's remaining values are all bigger than everything written so far, and already in order, so copy them straight on.

Smaller front: goes into the result, and its finger moves on.
One list empty: copy the rest of the other.
In code
a, b = [1, 4], [2, 3]
front = min(a[0], b[0])   # 1
Merge [2, 5, 8] and [1, 6, 7]. Row 1 and 2 are the lists, row 3 is the result.
012345
first
2
5
8
second
1
6
7
merged
1

Compare the fronts 2 and 1. The 1 is smaller, so it goes first.

Move 1 of 6

Ties and stability

What if both fronts are equal? Take the one from the first list. It changes nothing for plain numbers, but when the values carry other information, like names, it keeps values that were equal in their original order. A sort that does this is called stable.

Using "less than or equal" for the first list is the small detail that makes the merge stable.

Equal fronts: take from the first list.
Stable: equal values keep their original order.
Quick check

The fronts of the two lists are 5 and 5. Which do you take?

  1. AThe one from the first list, then the other next
  2. BNeither, because they're equal
  3. CBoth at the same time
Show the answer

The one from the first list, then the other next. Either gives the same numbers, but taking from the first list keeps equal values in their original order.

Your problem

Merge two sorted lists

a and b are two lists of whole numbers, each already sorted from smallest to largest. Return one list containing all the values of both, sorted from smallest to largest.

Example
a = [1, 4, 7], b = [2, 3, 9] → [1, 2, 3, 4, 7, 9]

0 ≤ length of each list ≤ 1,500 · −1,000,000 ≤ value ≤ 1,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve