0

作为一项任务,我必须实现归并排序。当我将数组作为参数传递时,我遇到了分段错误。一切似乎都是正确的。我附上代码。
arrint arr[1000],我将它传递给mergesortas
mergesort(arr, 0, n);

其余代码如下。

void merge(int a[], int l, int m, int r)
{
    int temp[r -l];
    int templ = l;
    int tempm = m;
    register int k; 
    for(k=0; k<(r-l); k++)
    {
    if((tempm >= r)||(templ < m)&&(a[templ] <= a[tempm]))
    {   /*if number from left subarray is smaller*/
    temp[k] = a[templ];
    templ++;
    }
    else
    {   /*number from right subarray is smaller*/
    temp[k] = a[tempm];
    tempm++;
    }
    }
    for(k= l; k< r; k++)
    {   /*copy results back to the array to be returned*/
    a[k] = temp[k - l];
    }
}

void mergesort(int ar[], int left, int right)
{
    int mid;    
    if(left < right)
    {
    mid= (left + right)/2;
    mergesort(&ar[0], left, mid - 1);
    mergesort(&ar[0], mid, right);
    merge(&ar[0], left, mid, right);
    }
}
4

1 回答 1

1

一旦你有left == 0and right == 1in mergesort,你将有一个无限递归:

void mergesort(int ar[], int left, int right) // IF LEFT IS 0 AND RIGHT IS 1 HERE...
{
    int mid;    
    if(left < right) // ...THEN LEFT IS LESS THAN RIGHT AND...
    {
    mid= (left + right)/2;
    mergesort(&ar[0], left, mid - 1);
    mergesort(&ar[0], mid, right); // ...HERE WE HAVE A CALL THAT IS
    // IDENTICAL TO THE ONE THAT GOT US HERE, INFINITE RECURSION
于 2013-03-10T21:38:45.817 回答