Consider two sorted integer arrays A and B in ascending order. We want two merge the two arrays to form a separate sorted array without violating the ascending order of the values. Implement the solution in C++ using primitive data types. What is the time complexity of populating the emerging array? guys i need your help please give me answer its urgent
Answers
Answer:
let's chat on whatsapp
Answer:
// Merge arrA[0..n1-1] and arrB[0..n2-1] into
// arrC[0..n1+n2-1]
void mergeArrays(int arrA[], int arrB[], int n1,
int n2, int arrC[])
{
int i = 0, j = 0, k = 0;
// Traverse both array
while (i<n1 && j <n2)
{
// Check if current element of first
// array is smaller than current element
// of second array. If yes, store first
// array element and increment first array
// index. Otherwise do same with second array
if (arrA[i] < arrB[j])
arrC[k++] = arrA[i++];
else
arrC[k++] = arrB[j++];
}
// Store remaining elements of first array
while (i < n1)
arrC[k++] = arrA[i++];
// Store remaining elements of second array
while (j < n2)
arrC[k++] = arrB[j++];
}
// Driver code
int main()
{
int arrA[] = {1, 3, 5, 7};
int n1 = sizeof(arrA) / sizeof(arrA[0]);
int arrB[] = {2, 4, 6, 8};
int n2 = sizeof(arrB) / sizeof(arrB[0]);
int arrC[n1+n2];
mergeArrays(arrA, arrB, n1, n2, arrC);
cout << "Array after merging" <<endl;
for (int i=0; i < n1+n2; i++)
cout << arrC[i] << " ";
return 0;
}
OUTPUT:
Array after merging
1 2 3 4 5 6 7 8