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 infact 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 ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


    

  • Tim

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

    • Techie Delight

      Thanks Tim for suggesting this optimized approach. We have added this in post. Please let us know if you find any more interesting methods to solve any problem. Happy coding!