In C++
You are given two arrays each of which is sorted. Write a method called mergeIt that takes the two arrays and merges them into one array. For instance, if you had 5, 9, 11 and 4, 6, 7 then you need to merge it to 4,5,6,7,9,11.
ANSWER : HERE IS THE ANSWER FOR YOUR QUESTION:
----------------------------------------------------------------------------------------------------------------
CODE:
#include<iostream>
using namespace std;
void mergeIt(int list1[], int list2[], int size1, int
size2)
{
int i = 0, j = 0, k = 0;
int list3[size1+size2];
// Traverse both array
while (i<size1 && j <size2)
{
if (list1[i] < list2[j])
list3[k++] =
list1[i++];
else
list3[k++] =
list2[j++];
}
// Store remaining elements of first array into the
merged array
while (i < size1)
list3[k++] = list1[i++];
// Store remaining elements of second array into
the merged array
while (j < size2)
list3[k++] = list2[j++];
cout << "When array got merged , resultant array
is :" <<endl;
for (int j=0; j < size1+size2; j++)
cout << list3[j] << "
";
}
int main()
{
//declaring arr1 array
int arr1[] = {10, 30, 40, 50,890,900};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
//declaring arr2 array
int arr2[] = {20, 25, 31, 100,130,200,450,600};
int n2 = sizeof(arr2) / sizeof(arr2[0]);
//calling the function mergeIt
mergeIt(arr1, arr2, n1, n2);
return 0;
}
----------------------------------------------------------------------------------------------------------------
SNIPPET:
----------------------------------------------------------------------------------------------------------------
OUTPUT:
----------------------------------------------------------------------------------------------------------------
I hope this would help you out.
If you like my answer , please upvote
If you have any doubt, you can provide comment /feedback below the answer
Thanks
Get Answers For Free
Most questions answered within 1 hours.