Expedia Interview Question
Software Engineer in TestsCountry: United States
public static int[] MergeSort(int[] A)
{
int[] temp = A.clone();
auxMergeSort(A,temp,0,A.length-1);
return temp;
}
public static void auxMergeSort(int[] A,int[] temp,int l,int h)
{
if(h -l == 0)
return;
if(h-l == 1)
{
if(A[h] < A[l])
{
int t = temp[h];
temp[h] = temp[l];
temp[l] = t;
A[h] = temp[h];
A[l] = temp[l];
return;
}
return;
}
if(l < h)
{
int m = (l + ((h - l) >> 1));
auxMergeSort(A, temp, l, m);
auxMergeSort(A, temp, m+1, h);
merge(A, temp,l,m,h);
}
}
public static void merge(int[] A, int[] temp,int l,int m,int h)
{
//A[l..m] is sorted and A[m+1..h] is sorted
int k = l;
int i = l, j = m +1;
while(i <= m && j <= h)
{
if(A[i] < A[j])
{
temp[k++] = A[i++];
}
else
{
temp[k++] = A[j++];
}
}
//Copy remaining elements
while(i <= m)
{
temp[k++] = A[i++];
}
System.out.println(" " + l + " , " + m + ", " + h);
System.out.println(Arrays.toString(temp));
//Dont need to copy second half
//Copy back the original array to reflect sorted order
for(int q = l ; q <= h; q++)
A[q] = temp[q];
}
Possible code below.
Idea is merge left and right halves recursively, and then merge them. While an in-place merge is possible, it is too complicated to code, and we use a scratch space.
Time complexity is O(n log n).
Space complexity is O(n), as we can reuse space between recursive calls, and presume the tmp array in the merge routine gets garbage collected at the end of call.
- Anonymous September 28, 2012