My first array M + N size and second array of size N.
let us say m=4,n=5
a[ ]= 1,3,5,7,0,0,0,0,0
b[ ]= 2,4,6,8,10
Now , how can i merge these two arrays without using external sorting algorithms and any other temporary array(inplace merge) but complexity should be o(n).Resultant array must be in sorted order.
Provided a is exactly the right size and arrays are already sorted (as seems to be the case), the following pseudo-code should help:
It’s basically a merge of the two lists into one, starting at the ends. Once
bfromhits -1, there are no more elements inbso the remainder inawere less than the lowest inb. Therefore the rest ofacan remain unchanged.If
aruns out first, then it’s a matter of transferring the rest ofbsince all theaelements have been transferred aboveatoalready.This is O(n) as requested and would result in something like:
Understanding that pseudo-code and translating it to your specific language is a job for you, now that you’ve declared it homework 🙂