#include <iostream>
void mergeTwoArraysIntoOne(const int* lhs, const int* rhs, int* dst, size_t numElements) {
const int* const endLhs = lhs + numElements;
const int* const endRhs = rhs + numElements;
for ( ; lhs < endLhs ; ) {
while (rhs < endRhs && *rhs < *lhs)
*(dst++) = *(rhs++);
*(dst++) = *(lhs++);
}
while (rhs < endRhs)
*(dst++) = *(rhs++);
}
void dumpArray(int* array, size_t elements) {
for (size_t i = 0; i < elements; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
}
int main() {
int array1[] = { 1, 2, 3 };
int array2[] = { 10, 20, 30 };
int array3[] = { 1, 11, 31 };
int result[6];
mergeTwoArraysIntoOne(array1, array2, result, 3);
dumpArray(result, 6);
mergeTwoArraysIntoOne(array2, array1, result, 3);
dumpArray(result, 6);
mergeTwoArraysIntoOne(array1, array3, result, 3);
dumpArray(result, 6);
mergeTwoArraysIntoOne(array3, array1, result, 3);
dumpArray(result, 6);
mergeTwoArraysIntoOne(array2, array3, result, 3);
dumpArray(result, 6);
mergeTwoArraysIntoOne(array3, array2, result, 3);
dumpArray(result, 6);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdm9pZCBtZXJnZVR3b0FycmF5c0ludG9PbmUoY29uc3QgaW50KiBsaHMsIGNvbnN0IGludCogcmhzLCBpbnQqIGRzdCwgc2l6ZV90IG51bUVsZW1lbnRzKSB7CiAgICBjb25zdCBpbnQqIGNvbnN0IGVuZExocyA9IGxocyArIG51bUVsZW1lbnRzOwogICAgY29uc3QgaW50KiBjb25zdCBlbmRSaHMgPSByaHMgKyBudW1FbGVtZW50czsKICAgIGZvciAoIDsgbGhzIDwgZW5kTGhzIDsgKSB7CiAgICAgICAgd2hpbGUgKHJocyA8IGVuZFJocyAmJiAqcmhzIDwgKmxocykKICAgICAgICAgICAgKihkc3QrKykgPSAqKHJocysrKTsKICAgICAgICAqKGRzdCsrKSA9ICoobGhzKyspOwogICAgfQogICAgd2hpbGUgKHJocyA8IGVuZFJocykKICAgICAgICAqK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