Reputation: 41
I'm trying to get my head round the recursive sort function that's part of the mergesort algorithm. Here's the code I have, which I'm almost certain is correct (following an online course).
private static void sort(Comparable[] a, Comparable[] aux, int low, int high) {
if (high <= low) return;
int mid = low + (high - low) / 2;
sort (a, aux, low, mid);
sort (a, aux, mid+1, high);
merge(a, aux, low, mid, high);
}
I understand what mergesort does- it breaks each subarray down into 2 smaller subarrays, repeating this until the subarrays are of length one (and by definition sorted), and then merges. However, the actual METHOD that this sort function uses to accomplish this is hard for me to follow. Maybe because I'm not used to recursive functions, but I was wondering if anyone can illuminate the order of operations and what the arguments are when the first merge occurs.
For example, when it hits the FIRST recursive call to sort(a, aux, low, mid) - does it break operation and not proceed to the second sort and the merge functions below, instead immediately calling sort again with the new parameters? When, in this case, would the second call to sort; sort(a, aux, mid+1, high); occur?
Thanks for any help. This is the first time I've posted here, if there are any formatting issues please let me know.
Upvotes: 4
Views: 351
Reputation: 457
Comments explaining each step in case you didn't get any:
if (high <= low) return; // if your high and low numbers are the same then this part of the loop is finished and it will start going back up
int mid = low + (high - low) / 2;//sets mid
sort (a, aux, low, mid);//recursively calls itself so that it will eventually hit the first if. This handles from low to mid
sort (a, aux, mid+1, high); //this handles from mid+1 to high
merge(a, aux, low, mid, high); //This is where the merge starts.
I find it helps to run a simple example and run through it over pen and paper if you're really having a hard time.
Upvotes: 1
Reputation: 3412
When it hits the FIRST recursive call to sort(a, aux, low, mid) - does it break operation and not proceed to the second sort and the merge functions below, instead immediately calling sort again with the new parameters?
When, in this case, would the second call to sort; sort(a, aux, mid+1, high); occur?
Upvotes: 2