Reputation: 15
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[] left = Arrays.copyOfRange(array, 0, array.length / 2);
int[] right = Arrays.copyOfRange(array, array.length / 2, array.length);
sort(left);
sort(right);
merge(left, right, 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 left contains 209 and right contains 47, then they merge, then it goes back to the original call where left contained 209 and 47, and right contains 16 and 82, except left is now sorted, and what I don't understand is that left and right 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, left contains the sorted elements {47, 209} that array contained when we finished calling merge. How did left'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.
Upvotes: 1
Views: 58
Reputation: 76
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!
Upvotes: 1