Answer on Question #72101- Programming & Computer Science - C++
Question:
Consider A, B, C as three arrays of size m, n and m + n respectively. Array A is stored in ascending order whereas array B is stored in descending order.
Write a C++ program to produce a third array C, containing all the data of arrays A and B and arranged in descending order. Display the data of array C only.
Answer:
#include <iostream>
using std::size_t;
using std::cout;
using std::endl;
void mergeTwoSortedArrays(const int *A, const size_t n, const int *B, const size_t m, int *C, const size_t k) {
size_t i = 0, j = m - 1, s = 0;
while (i < n and j >= 0 and s < k) {
if (A[i] < B[j])
C[s++] = A[i++];
else
C[s++] = B[j--];
}
while (i < n and s < k)
C[s++] = A[i++];
while (j >= 0 and s < k)
C[s++] = B[j--];
}
int main() {
const size_t n = 5;
int A[n] = { -5, 2, 3, 7, 9 };
const size_t m = 6;
int B[m] = { 9, 4, 3, 1, -1, -10 };
const size_t k = n + m;
int C[k] = {};
int C2[k] = {};
mergeTwoSortedArrays(A, n, B, m, C, k);
for (size_t s = 0; s < k; s++)
cout << C[s] << " ";
cout << endl;
mergeTwoSortedArrays(A, n - 1, B, m - 3, C2, k);
for (size_t s = 0; s < k; s++)
cout << C2[s] << " ";
cout << endl;
}Answer provided by https://www.AssignmentExpert.com
Comments