Microsoft Interview Question Software Engineer / Developers
0of 0 votesGiven two sorted arrays where the size of second array is large enough to hold the first array, write code to merge them (in sorted order). Write test cases
Algorithm:-
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.
int [] MergeSortedArray(int FirstArray[], int elementCountInFirstArray, int SecondArray[], int sizeofSecondArray){ int i=0,j=0; while(i<elementCountInFirstArray){ if(FirstArray[i] >= SecondArray[j]){ if(FirstArray[i] == SecondArray[j]){ i++; } int k= i; while(k<elementCountInFirstArray){ FirstArray[k+1] = FirstArray[k]; k++; } FirstArray[i]=SecondArray[j]; j++; elementCountInFirstArray++; } i++; } while(j<sizeofSecondArray){ FirstArray[i++] = SecondArray[j++]; } return FirstArray; }Please feel free to comment.
- Ankush Bindlish on November 27, 2009 Edit | Flag ReplyThanks
Ankush