我在这个C++合并中做错了什么

What am I doing wrong in this C++ mergesort?

本文关键字:错了 什么 合并 C++      更新时间:2023-10-16

程序正确编译并运行。整数列表是从输入文件中读取的,但输出显示这些数字时没有任何更改。我希望他们能从最小到最大排序。作为参考,我正在尝试实现一个类似于维基百科上的示例的版本。

// 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

我还没有深入研究您的代码,但这个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部分做了不同的事情。据我所知,这里是一样的。