Given two array of size n and m, Merge two sorted arrays.
Example 1:
Input:
N=4 M =4
arr1[] = {1, 2, 3 , 4}
arr2[] = {3, 4, 9 , 11}
Output: {1, 2, 3 , 3, 4, 4, 9 , 11}
Example 2:
Input:
N=5 M =5
arr1[] = {1, 2, 3 , 4, 9}
arr2[] = {3, 4, 9 , 11, 22}
Output: {1, 2, 3, 3, 4, 4, 9 , 9, 11, 22}
1. Input Reading:-The code starts by reading two integers, n and m, which represent the sizes
of the two input arrays.
It then initializes two arrays, arr1 and arr2, of sizes n and m, respectively.
The elements of arr1 and arr2 are read from the standard input using cin.
2. Merging Process:-
An array arr3 of size n + m is initialized to store the merged elements.
Three integer variables, i, j, and k, are initialized to keep track of the current positions in arr1, arr2,
and arr3, respectively.
A while loop is used to merge elements from arr1 and arr2 into arr3 while maintaining the sorted order. This
loop runs until either arr1 or arr2 is fully processed.
If the current element from arr1 is smaller than the current element from arr2, it is inserted into arr3,
and both i and k are incremented.
Otherwise, if the current element from arr2 is smaller or equal, it is inserted into arr3, and both j and k
are incremented.
After the first while loop, one of the input arrays (arr1 or arr2) may still have remaining elements. Two
more while loops copy any remaining elements from arr1 and arr2 to arr3.
3. Sorting the Merged Array:-After merging, the sort function is used to sort the merged array arr3 in ascending order. Sorting is
required because the merged elements may not be in sorted order initially.
4. Output:-
Finally, the code prints the sorted merged array arr3 with space-separated elements to the standard output
using a for loop.