-
Idea: Split the problem in half, sort the halves, then merge them
-
Then, you can split the sub-halves into halves as well, sort them, etc.
etc.
-
Stop splitting when you have a half that is only one value (it is sorted
already!)
-
It is much easier to describe this algorithm using recursion
than it is to describe it with a loop
static void Mergesort(int A[], int low, int high)
{
int mid;
if (low>=high) // then only one value, so we're done
return;
mid = (low+high)/2;
Mergesort(A,low,mid);
Mergesort(A,mid+1,high);
Merge(A,low,mid,high);
}
-
In this method, low and high are the endpoint indices
that the current call of Mergesort is considering (so, in the first call,
low==0 and high==A.length-1)
-
This is all that the Mergesort method needs to be, but what about the method
Merge that it uses? Well, that's a little more complex, but not much.
-
Merge needs to take two sorted sequences of values, and combine them into
one sorted sequence:
-
Idea: work along the sequences, taking the lowest value from either sequence
at each step and copy it into a holding array
-
Note: you need to declare this holding array and create it using new.
It should be just big enough to hold the portion being dealt with -- i.e.,
its size should be (high-low+1)
-
Note: they most likely do not alternate: one sequence might be all
lower than the other. So you need to handle these types of cases (as explained
in the next three steps)
-
Start at the beginning of each sequence. Keep current indices into each
sequence
-
one sequence starts at low and goes to mid; the other
starts at mid+1 and goes to high
-
While you're not at the end of either sequence, take the lowest value from
one of the sequences, copy it into the holding array, update its current
index, and continue
-
After that while loop, only one sequence has been fully consumed. Take
the other one and finish copying its values into the holding array
-
Now, copy the holding array back into the original array, from indices
low to high. This leaves that portion of the array sorted