Given two sorted arrays, X[] and Y[] of size m and n each, merge elements of X[] with elements of array Y[] by maintaining the sorted order, i.e., fill X[] with the first m smallest elements and fill Y[] with remaining elements.

Do the conversion in-place and without using any other data structure.

 
For example,

Input:
 
X[] = { 1, 4, 7, 8, 10 }
Y[] = { 2, 3, 9 }
 
Output:
 
X[] = { 1, 2, 3, 4, 7 }
Y[] = { 8, 9, 10 }

Practice this problem

The idea is simple. Consider each array element X[] and ignore it if it is already in the correct order (i.e., the element smallest among all remaining elements); otherwise, swap it with the smallest element, which happens to be the first element of Y[]. After swapping, move the element (now present at Y[0]) to its correct position in Y[] to maintain the sorted order.

 
Following is the implementation in C++, Java, and Python based on the above idea. The merge process is almost similar to the merge routine of the merge sort algorithm. The only difference is that we are not using an auxiliary array for merging.

C++


Download  Run Code

Output:

X: 1 2 3 4 7
Y: 8 9 10

Java


Download  Run Code

Output:

X: [1, 2, 3, 4, 7]
Y: [8, 9, 10]

Python


Download  Run Code

Output:

X: [1, 2, 3, 4, 7]
Y: [8, 9, 10]

The time complexity of the above solution is O(m.n), where m is the size of the first array and n is the size of the second array. The solution doesn’t require any extra space. The problem, in fact, can be solved in linear time and constant space. This approach is highly complicated and is discussed here. Thanks to Tim for suggesting this optimized approach in the comments.