程序编译并正常运行。从输入文件中读取整数列表,但输出显示这些数字而不做任何更改。我希望它们从最小到最大排序。作为参考,我正在尝试实现类似于维基百科上的示例的版本。
// arrA contains items to sort; arrB is an array to work in
void mergesort(int *arrA, int *arrB, int first, int last) {
// a 1 element array is already sorted
// make increasingly longer sorted lists
for (int width = 1; width < last; width = 2 * width) {
// arrA is made up of 1 or more sorted lists of size width
for (int i = 0; i < last; i += 2 * width) {
// merge two sorted lists
// or copy arrA to arrB if arrA is full
merge(arrA, i, min(i+width, last), min (i + 2 * width,
last), arrB);
} // end for
// now arrB is full of sorted lists of size 2* width
// copy arrB into arrA for next iteration
copy(arrB, arrA, last);
} // end for
} // end mergesort
void merge(int *arrA, int iLeft, int iRight, int iEnd, int *arrB) {
int i0 = iLeft, i1 = iRight;
// while either list contains integers
for (int j = iLeft; j < iEnd; j++) {
// if 1st integer in left list is <= 1st integer of right list
if (i0 < iRight && (i1 >= iEnd || arrA[i0] <= arrA[i1])) {
arrB[j] = arrA[i0];
i0 += 1;
} // end if
else { // right head > left head
arrB[j] = arrA[i0];
i0 += 1;
} // end else
} // end for
} // end merge
void copy(int *origin, int *destination, int size) {
for (int i = 0; i < size; i++) {
destination[i] = origin[i];
} // end for
} // end copy
int main() {
int size = 0, first = 0, *arrA, *arrB;
// input data
read(&arrA, &arrB, &size);
// sorting
mergesort(arrA, arrB, first, size);
// output
write(arrA, first, size);
// cleanup
delete [] arrA;
delete [] arrB;
}
33 9 -2
33 9 -2
答案 0 :(得分:5)
我没有深入研究你的代码,但这个if语句对我来说似乎有点不对:
if (i0 < iRight && (i1 >= iEnd || arrA[i0] <= arrA[i1])) {
arrB[j] = arrA[i0];
i0 += 1;
} // end if
else { // right head > left head
arrB[j] = arrA[i0];
i0 += 1;
} // end else
当然,一对if / else子句的重点在于你在if和else部分做了不同的事情。据我所知,这里的情况完全相同。