I've seen many mergesort implementations. Here is the version in Data Structures and Algorithms in Java (2nd Edition) by Robert Lafore:
private void recMergeSort(long[] workSpace, int lowerBound,int upperBound)
{
if(lowerBound == upperBound) // if range is 1,
return; // no use sorting
else
{ // find midpoint
int mid = (lowerBound+upperBound) / 2;
// sort low half
recMergeSort(workSpace, lowerBound, mid);
// sort high half
recMergeSort(workSpace, mid+1, upperBound);
// merge them
merge(workSpace, lowerBound, mid+1, upperBound);
} // end else
} // end recMergeSort()
private void merge(long[] workSpace, int lowPtr,
int highPtr, int upperBound)
{
int j = 0; // workspace index
int lowerBound = lowPtr;
int mid = highPtr-1;
int n = upperBound-lowerBound+1; // # of items
while(lowPtr <= mid && highPtr <= upperBound)
if( theArray[lowPtr] < theArray[highPtr] )
workSpace[j++] = theArray[lowPtr++];
else
workSpace[j++] = theArray[highPtr++];
while(lowPtr <= mid)
workSpace[j++] = theArray[lowPtr++];
while(highPtr <= upperBound)
workSpace[j++] = theArray[highPtr++];
for(j=0; j<n; j++)
theArray[lowerBound+j] = workSpace[j];
} // end merge()
One interesting thing about the merge method is that almost all the implementations didn't pass the mid
parameter to the merge method. mid
is calculated in the merge. This is strange, since highPtr
is assigned to mid + 1
from the calling method.
Why did the author not pass mid
to merge like merge(workSpace, lowerBound,mid, mid+1, upperBound);
? If we write it like , we can easily see that [lowerBound,mid] is the lower range ,[mid+1,upperBound] is higher range.
I think there must be a reason, otherwise I can't understand why all implementations of an algorithm older than half a century are coincident in the such a little detail.