eladyanai22
BAN USERIn case that array 2 is long enough to accommodate both of the arrays then its is filled its size minus array 1's size. (len2-len1 = biggest number on array 2)
int* mergeSort(int* arr1, int len1, int* arr2, int len2)
{
int* runner = arr2 + len2 -1; //will mark the cell we want to place the bigger number
int realLen2 = len2 - len1; //the actual length of array2- the values for the merge
int* endOfArr1 = arr1 + len1 -1; //the end of array1 which is the biggest number.
int* endOfArr2 = arr2 + realLen2 -1; //the biggest number on array2
//run until you reach the end of one of the arrays
//it will always be completely sorted by then.
while(len1 > 0 && realLen2 > 0)
{
if(*endOfArr1 >= *endOfArr2)
{
*runner = *endOfArr1;
endOfArr1--;
len1--;
}
else
{
*runner = *endOfArr2;
endOfArr2--;
realLen2--;
}
runner--;
}
//in case there are leftovers in array1 merge them (in case all array1 is smaller)
while(len1 > 0)
{
*runner = *endOfArr1;
endOfArr1--;
len1--;
runner--;
}
return arr2;
}
In case that array 2 is long enough to accommodate both of the arrays then its is filled its size minus array 1's size. (len2-len1 = biggest number on array 2)
int* mergeSort(int* arr1, int len1, int* arr2, int len2)
{
int* runner = arr2 + len2 -1; //will mark the cell we want to place the bigger number
int realLen2 = len2 - len1; //the actual length of array2- the values for the merge
int* endOfArr1 = arr1 + len1 -1; //the end of array1 which is the biggest number.
int* endOfArr2 = arr2 + realLen2 -1; //the biggest number on array2
//run until you reach the end of one of the arrays
//it will always be completely sorted by then.
while(len1 > 0 && realLen2 > 0)
{
if(*endOfArr1 >= *endOfArr2)
{
*runner = *endOfArr1;
endOfArr1--;
len1--;
}
else
{
*runner = *endOfArr2;
endOfArr2--;
realLen2--;
}
runner--;
}
//in case there are leftovers in array1 merge them (in case all array1 is smaller)
while(len1 > 0)
{
*runner = *endOfArr1;
endOfArr1--;
len1--;
runner--;
}
return arr2;
}
(above was my answer- i was just not signed in)
BTW- if all of the rows contains all ones than return the first row is fine.
exact same solution I wrote on my notebook while solving it, but I missed the q.add(null) to separate the lines. nice one!
- eladyanai22 January 24, 2015