data-structures · intermediate · ~15 min
The merge step of mergesort.
Merge two already-sorted arrays into one sorted array.
Implement void merge_sorted(const int *a, size_t na, const int *b, size_t nb, int *out) that merges the two sorted input arrays into out so that out holds all na+nb values in non-decreasing order.
a: sorted array of na ints (read-only).b: sorted array of nb ints (read-only).out: writable array with room for na+nb ints.Nothing returned; out[0..na+nb-1] contains the merged, sorted sequence.
a={1,3,5}, b={2,4,6} -> out={1,2,3,4,5,6}
a={1,2,3}, b={} -> out={1,2,3}
a (na sorted ints), b (nb sorted ints), out (room for na+nb ints).
Nothing returned; out holds all values merged in non-decreasing order.
Both inputs are sorted; merge in O(na+nb).
#include <stddef.h>
void merge_sorted(const int *a, size_t na, const int *b, size_t nb, int *out) { /* TODO */ }
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.