BeginnerCoder

Lesson 15 — Merge sorted lists

Merge two sorted lists

Given two lists that are already sorted, you can combine them into one sorted list in a single pass. Keep one pointer in each list. Compare the two front items, take the smaller one, and move that pointer forward. When one list runs out, add whatever is left of the other.

# [1, 5] and [2, 3]: take 1, take 2, take 3, then add [5]

Why it matters: merging is the heart of merge sort (Lesson 24) and of combining sorted files or database results.

Want it another way?
Task

Inside the loop, append the smaller front item and move its pointer. Expected: [1, 2, 3, 4, 5, 6, 8].

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.