以下合并排序来自数据结构和算法分析(Weiss)。我想知道的是for
合并步骤的最后一个循环。我知道我们必须复制tmpArray
回array
,但我不明白为什么我们这样做 from rightend
,以及为什么我们没有i
go from 0
to tmpArray.size
。有人可以解释一下吗?
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
}