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,


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

Output:
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.

C++

Download   Run Code

Java

Download   Run Code



Output:


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.

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
Tim
Guest

This is a nice algorithm, but linear-time, constant-space (but extremely complicated) algorithms do in fact exist — see for example http://www.akira.ruc.dk/%7Ekeld/teaching/algoritmedesign_f04/Artikler/04/Huang88.pdf. (Though I certainly would not expect anyone to describe this algorithm in an interview situation!)

xiaoomai
Guest

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

yndi
Guest

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).

Aditya
Guest

That won’t be in-place right?

yndi
Guest

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)))

Aman
Guest