Solution: The trick to solving this problem is to start filling the destination array from the back with the largest elements. You will end up with a merged and sorted destination array.
Code (C#):
// A1 and A2 are two sorted arrays.
// A2 is not completely full (has empty slots at the end and are exactly the
// size of A1)
// the goal is to merge the two arrays in a sorted fashion
void Merge(int[] A1, int[] A2)
{
int count = FindCount(A2); // get the count of full slots
int i = A1.Length - 1;
int j = count - 1;
int k = A2.Length - 1;
for(;k>=0;k--)
{
if(A1[i] > A2[j] || j < 0)
{
A2[k] =A1[i];
i--;
}
else
{
A2[k] = A2[j];
j--;
}
}
}
6 comments: