Interview Questions

Consider 2 integer Arrays A and B .....

Software QA/Tests Interview Questions from Microsoft


(Continued from previous question...)

Consider 2 integer Arrays A and B .....

Question:
Consider 2 integer Arrays A and B. The elements in both arrays are arranged in ascending order. One of the arrays has exact sufficient space at the end to accommodate the other. Write a function to merge both arrays in ascending order and place it in the largest array.


maybe an answer:


void mergeArray(int* arr1, int n1, int* arr2, int n2)
{
int i, j, k;

i = n1-1;
j = n2-1;
k = n1+n2-1;


while(i>=0 && j>=0 && k >= 0)
{
if(arr1[i] >= arr2[j])
{
arr1[k] = arr1[i];
--k; --i;
}
else
{
arr1[k] = arr2[j];
--k; --j;
}
}
while(i>=0)
{
arr1[k--] = arr1[i--];
}
while(j>=0)
{
arr1[k--] = arr2[i--];
}
}



maybe an answer2:


public static void Merge(int[] A, int[] B)
{
if (A == null || B == null)
return;
if (A.Length > B.Length)
{
Merge(B, A, B.Length, A.Length - B.Length);
}
else
{
Merge(A, B, A.Length, B.Length - A.Length);
}
}
private static void Merge(int[] min, int[] max, int minCount, int maxCount)
{
int i = minCount - 1, j = maxCount - 1;
int m = max.Length - 1;
while (i >= 0 && j >= 0)
{
if (min[i] > max[j])
{
max[m] = min[i];
i--;
}
else
{
max[m] = max[j];
j--;
}
m--;
}
if (j == -1)
Array.Copy(min, max, i + 1);

(Continued on next question...)

Other Interview Questions