我尝试从此wikipedia page采用自上而下的合并排序算法并将其转换为C代码,但结果并未产生正确的结果。
这是代码:
#include <stdio.h>
int A[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int B[10]; //sorted array
int n;
void TopDownMergeSort(int A[], int B[],int n);
void TopDownSplitMerge(int B[], int iBegin, int iEnd, int A[]);
void TopDownMerge(int A[], int iBegin, int iMiddle, int iEnd, int B[]);
void CopyArray(int A[], int iBegin, int iEnd, int B[]);
int main()
{
TopDownMergeSort(A, B, 10);
for(int i = 0;i < 10;i++) {
printf("%i ", B[i]);
}
printf("\n");
return 0;
}
// Array A[] has the items to sort; array B[] is a work array.
void TopDownMergeSort(int A[], int B[], int n)
{
CopyArray(A, 0, n, B); // duplicate array A[] into B[]
TopDownSplitMerge(B, 0, n, A); // sort data from B[] into A[]
}
// Sort the given run of array A[] using array B[] as a source.
// iBegin is inclusive; iEnd is exclusive (A[iEnd] is not in the set).
void TopDownSplitMerge(int B[], int iBegin, int iEnd, int A[])
{
if(iEnd - iBegin < 2) // if run size == 1
return; // consider it sorted
// split the run longer than 1 item into halves
int iMiddle = (iEnd + iBegin) / 2; // iMiddle = mid point
// recursively sort both runs from array A[] into B[]
TopDownSplitMerge(A, iBegin, iMiddle, B); // sort the left run
TopDownSplitMerge(A, iMiddle, iEnd, B); // sort the right run
// merge the resulting runs from array B[] into A[]
TopDownMerge(B, iBegin, iMiddle, iEnd, A);
}
void TopDownMerge(int A[], int iBegin, int iMiddle, int iEnd, int B[])
{
// Left source half is A[ iBegin:iMiddle-1].
// Right source half is A[iMiddle:iEnd-1
// While there are elements in the left or right runs...
for (int k = iBegin; k < iEnd; k++) {
// If left run head exists and is <= existing right run head.
if (i < iMiddle && (j >= iEnd || A[i] <= A[j])) {
B[k] = A[i];
i = i + 1;
} else {
B[k] = A[j];
j = j + 1;
}
}
printf("Sort result 1: ");
for(int i = 0; i < 10; i++) {
printf("%i ", A[i]);
}
printf("\n");
}
void CopyArray(int A[], int iBegin, int iEnd, int B[])
{
for(int k = iBegin; k < iEnd; k++)
B[k] = A[k];
}
在给定列表上运行此代码会生成结果6, 7, 8, 9, 10, 1, 2, 3, 4, 5
,并且通常运行给定列表会生成一个列表,其中包含两个未合并的已排序的半部分。我尽可能忠实地复制算法,但我似乎无法弄清问题出在哪里。
答案 0 :(得分:1)
维基百科文章中的代码有一个错误。
在TopDownMergeSort
中,行:
TopDownSplitMerge(B, 0, n, A); // sort data from B[] into A[]
错了。 A[]
是来源,B[]
是目的地。这是更正的代码行:
TopDownSplitMerge(A, 0, n, B); // sort data from A[] into B[]