Hello everyone. I'm new to java. I'm trying to solve a merge sort problem and I'm stuck.
the following is what I've written so far, of a function that takes two presorted arrays of integers and is supposed to merge sort them into one:
This works until either i or j meets its limit in the for loop.
In pseudo code, I know that I have to say something like:
"If either i or j is out of range then exit this portion of the loop and take all of the remaining integers in the other array (i.e. the array that hasn't been traversed) and put them into the result set"
but i'm having trouble telling it to do this, since something like if(array1=null) doesn't seem to be acceptable syntax.
can somebody give me a hint? - thanks.
I am a nobody, and nobody is perfect; therefore, I am perfect.
the following is what I've written so far, of a function that takes two presorted arrays of integers and is supposed to merge sort them into one:
Code:
public static int[] mergeSort(int[] array1, int[] array2)
{
int a1Len=array1.length;
int a2Len=array2.length;
int resultLen=array1.length+array2.length;
int[] resultSet=new int[resultLen];
int r=0;
for(int i=0;i<a1Len;)
{
for(int j=0;j<a2Len;)
{
if(array1[i]<array2[j])
{
resultSet[r]=array1[i];
r++;
i++;
}
else
{
resultSet[r]=array2[j];
r++;
j++;
}
}
}
return resultSet;
}
This works until either i or j meets its limit in the for loop.
In pseudo code, I know that I have to say something like:
"If either i or j is out of range then exit this portion of the loop and take all of the remaining integers in the other array (i.e. the array that hasn't been traversed) and put them into the result set"
but i'm having trouble telling it to do this, since something like if(array1=null) doesn't seem to be acceptable syntax.
can somebody give me a hint? - thanks.
I am a nobody, and nobody is perfect; therefore, I am perfect.