fork(1) download
  1. #include <iostream>
  2.  
  3. void mergeTwoArraysIntoOne(const int* lhs, const int* rhs, int* dst, size_t numElements) {
  4. const int* const endLhs = lhs + numElements;
  5. const int* const endRhs = rhs + numElements;
  6. for ( ; lhs < endLhs ; ) {
  7. while (rhs < endRhs && *rhs < *lhs)
  8. *(dst++) = *(rhs++);
  9. *(dst++) = *(lhs++);
  10. }
  11. while (rhs < endRhs)
  12. *(dst++) = *(rhs++);
  13. }
  14.  
  15. void dumpArray(int* array, size_t elements) {
  16. for (size_t i = 0; i < elements; ++i)
  17. std::cout << array[i] << " ";
  18. std::cout << std::endl;
  19. }
  20.  
  21. int main() {
  22. int array1[] = { 1, 2, 3 };
  23. int array2[] = { 10, 20, 30 };
  24. int array3[] = { 1, 11, 31 };
  25.  
  26. int result[6];
  27.  
  28. mergeTwoArraysIntoOne(array1, array2, result, 3);
  29. dumpArray(result, 6);
  30.  
  31. mergeTwoArraysIntoOne(array2, array1, result, 3);
  32. dumpArray(result, 6);
  33.  
  34. mergeTwoArraysIntoOne(array1, array3, result, 3);
  35. dumpArray(result, 6);
  36.  
  37. mergeTwoArraysIntoOne(array3, array1, result, 3);
  38. dumpArray(result, 6);
  39.  
  40. mergeTwoArraysIntoOne(array2, array3, result, 3);
  41. dumpArray(result, 6);
  42.  
  43. mergeTwoArraysIntoOne(array3, array2, result, 3);
  44. dumpArray(result, 6);
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
1 2 3 10 20 30 
1 2 3 10 20 30 
1 1 2 3 11 31 
1 1 2 3 11 31 
1 10 11 20 30 31 
1 10 11 20 30 31