PythiloLesson 8 of 8 · progress kept in this browser

Merge sorted streams without sorting again

Two sorted sources already contain most of the ordering information. Compare their next values and advance only the source chosen. Taking the left source on equality preserves its order relative to the right source. The same pattern supports merge sort, sorted file processing and joining ordered event streams.

left = [1, 4]
right = [2, 3]
print(left[0] <= right[0])
Your task

Write merge_sorted(left, right), returning a new sorted list from two already-sorted lists. Preserve duplicates, do not call sorted or list.sort, and do not change the inputs.

All lessons