在我的合并排序方法中,我还有一个合并函数,我认为它正常工作,因为我在其他地方测试过。但是,当我尝试合并排序作为一个整体时,数字不能正确排序。 编辑:添加合并
代码:
void mergeSort( int A[], int p, int q )
// PRE: p >= 0; q >= 0; A[p..q] is initialized
// POST: A[p..q] is sorted in ascending order
{
int i; // counter used to initialize L and R
int j;
int m; // midpoint of A
int L[100]; // lower half of A
int R[100]; // upper half of A
if ( p < q ) // if list contains more than one value
{
m = ( p + q ) / 2; // find midpoint
j = 0;
for ( i = p; i <= m; i++ ) // initialize lower half of array
{
L[j] = A[i];
j++;
}
j = 0;
for ( i = m + 1; i <= q; i++ ) // initialize upper half of array
{
R[j] = A[i];
j++;
}
mergeSort( A, p, m ); // call mergeSort for lower half of array
mergeSort( A, m + 1, q ); // call mergeSort for upper half of array
merge( L, R, m - p + 1, q - m, A ); // merge both sides
}
}
void merge( int L[], int R[], int l_size, int r_size, int A[] )
// PRE: l_size > 0; r_size > 0; L[0..l_size-1] is in ascending order;
// R[0..r_size-1] is in ascending order; A is allocated to l_size + r_size
// POST: A[0..l_size+r_size-1] contains all elements of L[0..l_size-1] and
R[0..r_size-1]
{
int i; // counter used to fill A at end of algorithm
int l_ctr; // counter used to traverse L
int r_ctr; // counter used to traverse R
int a_ctr; // counter used to traverse A
l_ctr = 0;
r_ctr = 0; // set all counters equal to zero
a_ctr = 0;
while ( l_ctr < l_size && r_ctr < r_size ) // loop runs until reaching end of a list
{
if ( L[l_ctr] < R[r_ctr] ) // if lowest remain ing value in L is
{ // lower than lowest remaining value in R;
A[a_ctr] = L[l_ctr]; // set next index of A to L[l_ctr]
l_ctr++; // increment l_ctr by one
}
else // else do the same for r_ctr
{
A[a_ctr] = R[r_ctr];
r_ctr++;
}
a_ctr++; // increment a_ctr by one
}
if ( l_ctr < l_size ) // if all of L has not been seen yet
{
for ( i = l_ctr; i < l_size; i++ ) // loop sets remaining values in L
{ // to the last values of A
A[a_ctr] = L[i];
a_ctr++;
}
}
else // else do the same for R
{
for ( i = r_ctr; i < r_size; i++ )
{
A[a_ctr] = R[i];
a_ctr++;
}
}
}
答案 0 :(得分:0)
您的合并步骤始终使用A[0]
作为目标来合并两个范围。您希望索引[p..m]
和[m+1..q]
描述的范围返回A[p..q]
。至少有两个简单的修复。
A+p
作为merge
的最后一个参数传递(或使用&A[p]
,它们相同)。p
作为附加参数传递给merge
,并使用它来初始化a_ctr
。选择其中一个进行测试。
编辑:
我在本地测试了您的代码,并且看到对mergeSort
的递归调用应该向上移动到您计算m
的行的下方。复制到临时数组的以下行属于合并过程,应该在递归调用之后。