Okay I'm having some trouble understanding how things are getting assigned here. I have the following code
public static void sort(int[] array)
{
if(array.length < 2)
{
return;
}
int[] s1 = Arrays.copyOfRange(array, 0, array.length / 2);
int[] s2 = Arrays.copyOfRange(array, array.length / 2, array.length);
sort(s1);
sort(s2);
merge(s1, s2, array);
}
okay, so say you have an 8 element array like {209, 47, 16, 82, 34, 552, 1995, 1024} Okay, so I get whats going on here, it calls and calls and calls and then eventually s1 contains 209 and s2 contains 47, then they merge, then it goes back to the original call where s1 contained 209 and 47, and s2 contains 16 and 82, except s1 is now sorted, and what I don't understand is that s1 and s2 that contain {209} and {47} respectively are getting merged into array, and then when it backtracks to that call where it was splitting the 4 elements into 2 sets of 2, s1 contains the sorted elements {47, 209} that array contained when we finished calling merge. How did s1's get arrays contents?? If anybody could help me understand this i'd greatly appreciate it The merge function is just basically merging the 2 into array, nothing else.
CodePudding user response:
From what I understand, you're asking how it is that after the first merge happens, how is it that the data basically goes up from array to s1.
The answer is basically that the program passes 's1' as 'array' into the sort function by reference. Thus, 'array' is just an alias for the array 's1'. This happens every time the sort function is called.
Hope that answered your question!