Reputation: 14740
The following mergesort is from Data Structures and Algorithm Analysis (Weiss). What I'm wondering about is the last for
loop on the merge step. I understand that we have to copy tmpArray
back into array
, but I don't understand why we do it from rightend
, and why we don't have i
go from 0
to tmpArray.size
. Can someone explain please?
public static void mergeSort( Comparable [ ] a )
{
Comparable [ ] tmpArray = new Comparable[ a.length ];
mergesort( a, tmpArray, 0, a.length - 1 );
}
public static void mergesort( Comparable [ ] a, Comparable [ ] tmpArray,
int left, int right )
{
if( left < right ) {
int center = ( left + right ) / 2;
mergesort( a, tmpArray, left, center );
mergesort( a, tmpArray, center + 1, right );
merge( a, tmpArray, left, center + 1, right );
}
}
public static void merge( Comparable [ ] a, Comparable [ ] tmpArray,
int leftPos, int rightPos, int rightEnd )
{
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos + 1;
while( leftPos <= leftEnd && rightPos <= rightEnd )
if( a[ leftPos ].compareTo( a[ rightPos ] ) <= 0 )
tmpArray[ tmpPos++ ] = a[ leftPos++ ];
else
tmpArray[ tmpPos++ ] = a[ rightPos++ ];
while( leftPos <= leftEnd ) // Copy rest of first half
tmpArray[ tmpPos++ ] = a[ leftPos++ ];
while( rightPos <= rightEnd ) // Copy rest of right half
tmpArray[ tmpPos++ ] = a[ rightPos++ ];
for( int i = 0; i < numElements; i++, rightEnd-- )
a[ rightEnd ] = tmpArray[ rightEnd ]; // Copy tmpArray back
}
Upvotes: 1
Views: 325
Reputation: 372704
I think the main reason to do things this way is because the value of rightPos
, the spot where the subarray starts, has been destructively modified by the inner loop (note the use of rightPos++
. Consequently, in order to write the value back properly, the last loop counts backwards down to where rightPos
originally was. Were it to just start at rightPos
and count forward, it would be writing to the wrong index.
That said, I don't see any reason to do it this way. It would be easier to just declare new variables and modify those values instead of destroying the inputs and doing extra gymnastics to recover the original values.
Hope this helps!
Upvotes: 1