Reputation: 2579
This is an interview question, so the usual bounds apply.
One array has size n and n elements. Second array has size n+m and m elements. Both the arrays are sorted. The question is to move all n+m elements into the second array in a sorted order. O(N) is desired.
There's no mention of not being able to use extra space, but going by the question, it doesn't seem to allow for additional space.
We can simultaneously walk the two arrays (a la Merge Sort) and combine them, but that would need an extra array or extra complexity of moving existing elements down by 1 (which would mean O(N2)).
Update: Here's an example.
Array1: {2, 4, 6, 10}
Array2: {21, 23, 25, , , , }
Answer: {2, 4, 6, 10, 21, 23, 25}
Upvotes: 1
Views: 774
Reputation: 20371
There's no mention of not being able to use extra space, but going by the question, it doesn't seem to allow for additional space.
You don't need any - you have n
elements in one array and m
elements in the other. You also have n+m
space in the other. It can clearly accommodate the union of the two arrays.
As mentioned in other answers, all you need to is :
/**
* Assumes both array are sorted in ascending order
* Array a has length n and contains n elements
* Array b has length m+n and contains m elements
* The merged, sorted array will be returned in b
*/
public void merge(int [] a, int [] b)
{
//b is the one with m+n space
int indexA = a.length - 1; //points to last element in a
int indexB = b.length - a.length - 1; //points to last element in b
int writeTo = b.length - 1; //points to last free position
while(indexA > -1 && indexB > -1)
{
if(a[indexA] > b[indexB])
{
b[writeTo--] = a[indexA--]
}
else
{
b[writeTo--] = b[indexB--];
}
}
//are there any elements left-over in a?
//any elements left-over in b will already be in their right place
while(indexA > -1)
{
b[writeTo--] = a[indexA--];
}
}
Upvotes: 3
Reputation: 29139
Walk the two arrays simultaneously, but from the back of the data rather than the start. Write the sorted data starting from the end of the larger array. You will never need to displace anything. Any data you overwrite will have already been written at its new location further down in the array... O(m+n)
Upvotes: 3