Merge two already-sorted arrays into one sorted array (e.g. [1,3,5] + [2,4,6] -> [1,2,3,4,5,6]).
Walk both arrays with two pointers, repeatedly taking the smaller front element, until one is exhausted; then append the remainder of the other. O(n + m) time. Concatenating and re-sorting works but wastes the existing order (O((n+m) log(n+m))).
public static int[] merge(int[] a, int[] b) {
int[] out = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
out[k++] = (a[i] <= b[j]) ? a[i++] : b[j++];
while (i < a.length) out[k++] = a[i++];
while (j < b.length) out[k++] = b[j++];
return out;
}function merge(a, b) {
const out = [];
let i = 0, j = 0;
while (i < a.length && j < b.length)
out.push(a[i] <= b[j] ? a[i++] : b[j++]);
return out.concat(a.slice(i), b.slice(j));
}def merge(a, b):
out, i, j = [], 0, 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
return out + a[i:] + b[j:]Merging sorted streams is the heart of merge sort and external sorting (combining sorted chunks that do not fit in memory).
A candidate concatenates then sorts. Why is the two-pointer merge better?