How do you merge two sorted arrays into a single sorted array, and what is the complexity?
Keep one pointer in each array and one pointer in the output. At each step, compare the values the two input pointers point at, copy the smaller one into the output, and advance that pointer. When one array is exhausted, append whatever remains of the other.
def merge_sorted(a, b):
merged = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
merged.append(a[i]); i += 1
else:
merged.append(b[j]); j += 1
merged.extend(a[i:])
merged.extend(b[j:])
return merged
print(merge_sorted([1, 3, 5], [2, 4, 6]))
print(merge_sorted([1, 2], []))The outputs are 1, 2, 3, 4, 5, 6 and 1, 2. The second call shows the empty-array case, where the loop never runs and the first array is appended unchanged.
The reason the merge is linear is that neither input is ever rescanned. Each element is compared once and copied once, so the total work is proportional to the combined length. That is the property that makes merge sort efficient: the merge step is O of n, and it is applied at every level of a logarithmic recursion tree, giving O of n log n overall.
The trade-off to name is space. This version allocates a third list, so it uses O of n extra memory and leaves both inputs untouched. That is usually the right choice, because keeping the inputs intact avoids aliasing bugs. The in-place variant, where the result overwrites one of the inputs, saves the extra array but requires the destination to have enough room and is noticeably more intricate to get right. As with any merge, using less-than-or-equal in the comparison keeps the sort stable, which matters when equal elements carry different payloads.