Merge two sorted lists
Inputs
first and second are lists of 0 to 8 whole numbers in increasing order, each from 0 to 30.
Your tasks
- Create an empty list
merged, and two markersiandj, both 0. - Use a
whileloop that runs while both lists still have numbers. Add the smaller offirst[i]andsecond[j]tomergedand move that marker on. If they are equal, take fromfirst. - After that loop, add whatever remains in either list.
- Complete
mergeSortedso it returnsmerged. Return it, do not print it.
Example
With first = [1, 4, 6] and second = [2, 4, 9], mergeSorted returns [1, 2, 4, 4, 6, 9].
Rules
- The result is in increasing order and keeps duplicates.
Test data
TEST DATA 1: first is [1, 4, 6], second is [2, 4, 9]
TEST DATA 2: first is [], second is [3]
Practice focus
Two pointers and sliding windows: loops that move two positions instead of one. Two pointers and sliding windows turn many quadratic answers into linear ones.