0

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

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

1 回答 1

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 部分做不同的事情。据我所知,这里是一样的。

于 2013-02-20T17:35:43.253 回答