![]() |
VOOZH | about |
Given two sorted arrays, arr[], brr[] of size N, and M, the task is to merge the two given arrays such that they form a sorted sequence of integers combining elements of both the arrays.
Examples:
Input: arr[] = {10}, brr[] = {2, 3}
Output: 2 3 10
Explanation: The merged sorted array obtained by taking all the elements from the both the arrays is {2, 3, 10}.
Therefore, the required output is 2 3 10.Input: arr[] = {1, 5, 9, 10, 15, 20}, brr[] = {2, 3, 8, 13}
Output: 1 2 3 5 8 9 10 13 15 20
Naive Approach: Refer to Merge two sorted arrays for the simplest approach to merge the two given arrays.
Time Complexity: O(N * M)
Auxiliary Space: O(1)
Space Optimized Approach: Refer to Merge two sorted arrays with O(1) extra space to merge the two given arrays without using any extra memory.
Time Complexity: O(N * M)
Auxiliary Space: O(1)
Efficient Space Optimized Approach: Refer to Efficiently merging two sorted arrays with O(1) extra space to merge the two given array without using any extra memory.
Time Complexity: O((N + M) * log(N + M))
Auxiliary Space: O(1)
Partition - based Approach: The idea is to consider the (N + 1)th element of the final sorted array as a pivot element and perform the quick sort partition around the pivot element. Finally, store the first N smaller elements of the final sorted array into the array, arr[] and the last M greater elements of the final sorted array into the array, brr[] in any order and sort both these arrays separately. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
1 2 4 5 7 9 10
Time Complexity: O((N + M)log(N + M))
Auxiliary Space: O(1)
Efficient Approach: Refer to merge two sorted arrays to efficiently merge the two given arrays.
Time Complexity: O(N + M)
Auxiliary Space: O(N + M)