Inplace merge two sorted arrays

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 first m smallest elements and fill Y[] with remaining elements.

The conversion should be done in-place and without using any other data structure.


For example,

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

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


The idea is very simple. We consider each element of array X[] and ignore the element if it is already in correct order (i.e. the element smallest among all remaining elements) else we swap it with smallest element which happens to be first element of Y. After swapping, we move the element (now present at Y[0]) to its correct position in Y[] to maintain the sorted order. The merge process is almost similar to merge routine of mergesort algorithm. The only difference is that we are not using an auxiliary array for merging.


Download   Run Code


Download   Run Code


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

The time complexity of above solution is O(mn) and auxiliary space used by the program is O(1). The problem can in fact be solved in linear time and constant space. This approach highly complicated and is discussed here. Thanks to Tim for suggesting this optimized approach in comments.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

newest oldest most voted
Notify of

This is a nice algorithm, but linear-time, constant-space (but extremely complicated) algorithms do in fact exist — see for example (Though I certainly would not expect anyone to describe this algorithm in an interview situation!)


It sounds simpler to just run heap sort on top of a wrapper of two arrays totally ignoring the sorted order, it runs in O((m+n)*log(m+n)) instead of O(mn).


That won’t be in-place right?


Why not? Heap sort works in-place. Quick sort will do too. It only needs to map indices to either x or y depending on whether the current index k is greater than m-1 (return &(x+k)) or not (return &(y+(k-m)))



this can be O(m + n) time complexity.