作为一项任务,我必须实施mergesort。当我将数组作为参数传递时,我遇到了分段错误。一切似乎都是正确的。我附上了代码
arr
为int arr[1000]
,我将其传递给mergesort
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);
}
}
答案 0 :(得分:1)
在left == 0
中有right == 1
和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