MergeSort给出分段错误

时间:2017-10-07 17:51:03

标签: c sorting

我使用这个合并排序程序来创建自己的程序:

https://gist.github.com/mycodeschool/9678029

我的程序给了我分段错误11.我似乎无法弄清楚什么是错的。请帮帮我。

我的program

#include<stdio.h>


int a[20],n, nl, nr,left[20],right[20];
void merge(int *l, int *r, int *x);
void mergesort(int *x, int v);


void main()
{
    int i;


    printf("Enter the number of the elements \n");
    scanf("%d", &n);
    printf("Enter the array elements \n");
    for(i=0; i<n; i++)
    scanf("%d", &a[i]);
    printf("The array before sorting: \n");
    for(i=0; i<n; i++)
    printf("%d \n", a[i]);


    mergesort(a,n);

    printf("The array after sorting: \n");
    for(i=0; i<n; i++)
    printf("%d \n", a[i]);

}


void merge(int *l, int *r, int *x)
{
    int i=0, j=0, k=0;
    while(i<nl && j<nr)
    {
        if(l[i]<=r[j])
        {
            x[k]=l[i];
            i++;
        }
        else
        {
            x[k]=r[j];
            j++;
        }
        k++;
    }
    while(i<nl)
    {
        x[k]=l[i];
        i++;
        k++;
    }
    while(j<nr)
    {
        x[k]=r[j];
        j++;
        k++;
    }
}

void mergesort(int *x, int v)
{
    int mid,i;
    if(n<2)
    return;
    mid=n/2;
    nl=mid;
    nr= n-mid;

    for(i=0; i<mid; i++)
    left[i]=x[i];


        for(i=mid; i<n; i++)
    right[i-mid]= x[i];

    mergesort(left, mid);
    mergesort(right,v-mid);
    merge(left, right, a);


}

如果有人帮助过我,我真的很感激。谢谢!

1 个答案:

答案 0 :(得分:-1)

这是一个合并排序程序的示例,可以通过网络谷歌轻松找到。

某些比较应该会告诉您代码出错的地方。

#include<stdio.h>

void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);

int main()
{
    int a[30],n,i;
    printf("Enter no of elements:");
    scanf("%d",&n);
    printf("Enter array elements:");

    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    mergesort(a,0,n-1);

    printf("\nSorted array is :");
    for(i=0;i<n;i++)
        printf("%d ",a[i]);

    return 0;
}

void mergesort(int a[],int i,int j)
{
    int mid;

    if(i<j)
    {
        mid=(i+j)/2;
        mergesort(a,i,mid);        //left recursion
        mergesort(a,mid+1,j);    //right recursion
        merge(a,i,mid,mid+1,j);    //merging of two sorted sub-arrays
    }
}

void merge(int a[],int i1,int j1,int i2,int j2)
{
    int temp[50];    //array used for merging
    int i,j,k;
    i=i1;    //beginning of the first list
    j=i2;    //beginning of the second list
    k=0;

    while(i<=j1 && j<=j2)    //while elements in both lists
    {
        if(a[i]<a[j])
            temp[k++]=a[i++];
        else
            temp[k++]=a[j++];
    }

    while(i<=j1)    //copy remaining elements of the first list
        temp[k++]=a[i++];

    while(j<=j2)    //copy remaining elements of the second list
        temp[k++]=a[j++];

    //Transfer elements from temp[] back to a[]
    for(i=i1,j=0;i<=j2;i++,j++)
        a[i]=temp[j];
}