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?
Answers
Answer:Method 1 (O(n1 * n2) Time and O(1) Extra Space)
Create an array arr3[] of size n1 + n2.
Copy all n1 elements of arr1[] to arr3[]
Traverse arr2[] and one by one insert elements (like insertion sort) of arr3[] to arr1[]. This step take O(n1 * n2) time.
We have discussed implementation of above method in Merge two sorted arrays with O(1) extra space
Method 2 (O(n1 + n2) Time and O(n1 + n2) Extra Space)
The idea is to use Merge function of Merge sort.
Create an array arr3[] of size n1 + n2.
Simultaneously traverse arr1[] and arr2[].
Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to next position in arr3[] and move ahead in arr3[] and the array whose element is picked.
If there are remaining elements in arr1[] or arr2[], copy them also in arr3[].
Answer:agr mil gya solution tu phir to mzy ha apky wsy konsy section se ho
Explanation: