Given two sorted arrays X[] and Y[] of size m and n each where m >= n and X[] has exactly n vacant cells, merge elements of Y[] in their correct position in array X[], i.e., merge (X, Y) by keeping the sorted order.

For example,

Input:
 
X[] = { 0, 2, 0, 3, 0, 5, 6, 0, 0 }
Y[] = { 1, 8, 9, 10, 15 }
 
The vacant cells in X[] is represented by 0
 
Output:
 
X[] = { 1, 2, 3, 5, 6, 8, 9, 10, 15 }

Practice this problem

The idea is simple – move non-empty elements of X[] at the beginning of X[] and then merge X[] with Y[] starting from the end. The merge process is similar to the merge routine of the merge sort algorithm.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

1 2 3 5 6 8 9 10 15

Java


Download  Run Code

Output:

[1, 2, 3, 5, 6, 8, 9, 10, 15]

Python


Download  Run Code

Output:

[1, 2, 3, 5, 6, 8, 9, 10, 15]

The time complexity of the above solution is O(m + n) and runs in constant space. Here, m and n are the size of the first and second array, respectively.

 
Exercise: Merge arrays in descending order