I'll solve it for the slightly simpler case of "the two arrays are already in one buffer".
// requires: array is a pointer to a buffer of numbers,
// such that from [array, array+middle) is sorted, and [array+middle, array+length)
// is also sorted.
void merge_inplace( int* array, int length );
// This halves the number "gap", rounding up. Unless the value was 1, in
// which case it returns 0.
int nextgap( int gap ) {
if (gap==1) return 0;
return (gap+1)/2;
}
void merge_inplace( int* array, int length ) {
int gap = nextgap(length); // about half of length
while (gap != 0)
{
int left = 0;
int right = left+gap;
while (right < length) {
// ensure elements at left and right are in correct relative order:
if (array[left] > array[right])
std::swap(array[left], array[right]);
// advance:
++left;
++right;
}
// repeat on a gap half-ish the size:
gap = nextgap(gap);
}
}
now operating on two different arrays requires some extra work/logic, but that is mainly about fiddling with the indexes.
The point is that when you have two arrays that are sorted and next to each other, one pass of this "merge far apart, then closer together" algorithm (which has log-length count of subloops; so O(n lg n) steps) is enough to sort it.