Microsoft Interview Question
Software Engineer / DevelopersAlgorithm:-
Let the two arrays be a[n], b[m+n+c]//m elements & c >=0
Let i be the iterator for a[]
Let j be the iterator for b[]
Let k be the position that needs to be filled
i = index for last element of a[] = n-1
j = index for last element of b[] = m-1
k = m+n-1;
while(i>=0 && j>=0)
{
if(a[i]>b[j])
b[k--] = a[i--]
else
b[k--] = b[j--]
}
while(i>=0)
{
b[k--] = a[i--];
}
int[] MergeSortedArray(int firstArray[],int secondArrady[], int firstSize,int secondSize){
int k = firstSize + secondSize-1;
while(firstSize>=0 && secondSize>=0)
{
if(a[firstSize]>b[secondSize])
{
b[k--] = a[firstSize--];
}
else
{
b[k--] = b[secondSize--];
}
}
while(i>0)
{
b[k--] = a[firstSize--];
}
}
Approach:
1. Set the iterator in both the array
2. Compare the item and do just increment, or increment with FirstArray right shift by one position.
3. Augment Second array to FirstArray if it still remains after first iterator finishes.
Please feel free to comment.
- Ankush Bindlish November 27, 2009Thanks
Ankush