mergeSort中除以无限循环的部分

时间:2017-11-18 18:50:27

标签: c algorithm sorting recursion

我试图在c中实现merge_sort(递归),但函数myMergesort似乎继续执行除法部分并且永远不会进入合并部分

我使用伪代码:

mergeSort (array A, index i, index f, array X)
/* Order A[i..f − 1] using X as auxiliary array */
if more than 1 element then
    m ← (i + f)/2 
    mergeSort(A, i, m, X)
    mergeSort(A, m, f, X) 
    merge(A, i, m, f, X)

我的代码是:

void myMergesort(int a[], int i ,int f,int x[]){
    nloop++;//global variable to count number of iterations
//if I don't do this infinite loop and segmentation fault
    if(nloop>20){
        printf("infinite loop :(\n");
        exit(EXIT_FAILURE);
    }

    if(f>1){
        printArr(a,i,f-1);//prints elements of arr a from i to f-1
        int m = (f+i)/2;
        printf("myMergesort(a,%d,%d,x)\n",i,m);
        myMergesort(a,i,m,x);
        printf("myMergesort(a,%d,%d,x)\n",m,f);
        myMergesort(a,m,f,x);
        merge(a,i,m,f,x);
    }
    else printf("this part of the array already ordered\n");

}

在包含5 1输出的数组上调用mergeSort:

myMergesor(a,0,2,x)
5 1 
myMergesor(a,0,1,x)
this part of the array already ordered
myMergesor(a,1,2,x)
1 
myMergesor(a,1,1,x)
this part of the array already ordered
myMergesor(a,1,2,x)
1 
myMergesor(a,1,1,x)
this part of the array already ordered
myMergesor(a,1,2,x)
1 
myMergesor(a,1,1,x)
this part of the array already ordered
myMergesor(a,1,2,x)
1 
myMergesor(a,1,1,x)
this part of the array already ordered
myMergesor(a,1,2,x)
1 
myMergesor(a,1,1,x)
this part of the array already ordered
myMergesor(a,1,2,x)
1 
myMergesor(a,1,1,x)
this part of the array already ordered
myMergesor(a,1,2,x)
1 
myMergesor(a,1,1,x)
infinite loop :(

我确信错误发生在myMergesort功能中,因为我检查过它从未进入合并部分; 但为了以防万一... 我这样称呼它是主要的:

int main(int argc, char *argv[]){
    //input of integers from command line
    int sequenza[argc-1];
    for(int i=1; i<argc; i++){
        sequenza[i-1]=atoi(argv[i]);
    }
    algoMergesort(sequenza,argc-1);
    //print result 
    printArr(sequenza,0,argc-2);
}

void algoMergesort(int a[], int n){
    int x[n];
    printf("myMergesor(a,0,%d,x)\n",n);
    myMergesort(a,0,n,x);
} 

提前谢谢

1 个答案:

答案 0 :(得分:1)

if语句的条件不正确(f>1)。

应检查从iff排除)的子阵列是否包含多个元素。但是f并没有给你这么大,它应该是f-i,所以将if更改为:

if (f-i>1) {