自下而上合并排序在执行时不执行任何操作

时间:2015-03-24 13:36:28

标签: c mergesort

int
cmpLong(void *a, void *b) {
    long aa = (long)a;
    long bb = (long)b;
    return aa - bb;
}
int main (int argc, char *argv[]) {
    void **A = (void **)malloc(sizeof(void *) * 5);
    long a = 3, b = 4, c = 1, d = 5, e = 6;
    int n = 0;
    int i;
    A[n++] = (void *)a;
    A[n++] = (void *)b;
    A[n++] = (void *)c;
    A[n++] = (void *)d;
    A[n++] = (void *)e;
    myMergesort(A, n, cmpLong);
    for (i = 0; i < n; i++) {
        printf("%ld\n", (long)A[i]);
    }
    return 0;
}
void merge(void **A, void **B, void **C, \
           int lenA, int lenB, int(cmp)(void *, void *)) {

    int i = 0, j = 0, k = 0;
    while (i < lenA && j < lenB) {
        if(cmp(A[i], B[j]) < 0) {

            C[k++] = A[i++];
        }
        else {
            C[k++] = B[j++];
        }
    }
    while (i < lenA) {
        C[k++] = A[i++];
    }
    while (j < lenB) {
        C[k++] = B[j++];
    }
}


void myMergesort(void **A, int n, int(cmp)(void *, void*)) {
    int i, j, width;
    void **tmp;
    tmp = (void **)malloc(sizeof(void *) * n);
    for (width = 1; width < n; width *= 2) {
        for (i = 0; i < n - width; i = width * 2) {
            if ((i+2*width) > n) {
                int extra = (i+2*width)%width;
                merge(A+i, A+i+width, tmp+i, width, width - extra, cmp);
            }
            else {
                merge(A+i, A+i+width, tmp+i, width, width, cmp);
            }
        }
        for (j = 0; j < n; j++) {
            A[j] = tmp[j];
        }
    }
    return;
}

代码编译但是当它运行时,没有任何反应,编译器不会做任何事情,但它也不会崩溃。我一直试图找出问题是几个小时,我似乎无法弄清楚问题是什么

1 个答案:

答案 0 :(得分:1)

你的问题在这里:

for (width = 1; width < n; width *= 2) {
    for (i = 0; i < n - width; i = width * 2) {

这会导致无限循环,因为i = width * 2每次都不会增加i

这不一定是你的代码中唯一的问题,但通过修复它你应该挺身而出。