Question: In C++ Define a function int * merge (int * p1, int len1, int * p2, int len2) that merges the arrays where the first

In C++

Define a function int * merge (int * p1, int len1, int * p2, int len2) that "merges" the arrays where the first array has base address p1 with length len1 and the second array has base address p2 with length len2. Additionally, the elements of both arrays are guaranteed to be in ascending order. The function should return a dynamically allocated array containing all the merged elements in ascending order. To merge, we start with the zero element of p1 or p2, whichever is smaller, followed by the next smallest element and so on until the elements of (at least) one of the arrays are exhausted. If there are still elements remaining to process from the other array, then we just tack them on at the end. The resulting array will contain all the elements from p1 and p2 in ascending order. You must use pointer notation throughout the function (no square brackets). Do not use shuffle and then sort the result. That's too slow!

As an example, suppose merge is called with the arrays nums1 and nums2 in the code below. Also suppose len1 and len2 are both 5.

Then the return array will have length 10 and contents {1, 3, 4, 6, 9 ,13, 14, 17, 18, 20}. #include using namespace std; void print(int * nums, int length); int * merge(int * p1, int len1, int * p2, int len2); int main() { int len1, len2; cin >> len1 >> len2; // these will change for testing purposes but are always less than or equal to 5. int nums1[] = {1,3,9,13,17}; int nums2[] = {4,6,14,18,20}; int * temp = merge(nums1,len1,nums2,len2) ; print(temp, len1 + len2) ; delete [] temp; return 0; } void print(int * nums, int length) { for (int i = 0; i < length;i++) cout << *(nums + i) << " "; cout << endl; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!