首页 > 解决方案 > 合并排序输入不能大于 8

问题描述

我正在尝试运行程序以接收最大 10^7 的输入。当我输入 8 或更高的数字作为元素数时,程序会一直显示分段错误。之前的元素都很好。我只包含了代码的必要部分。是因为递归还是内存分配。此外,如果我们可以将数组作为动态分配包含为 *b=malloc(n) 会起作用吗?

    void merge(int a[], int low, int mid, int high)
    {  
    int i, j, k, n,index; 
    n=high-low+1;
    int b[n];
    i=low; j=mid+1; index=low; 
    while ( i<=mid && j<=high ) 
    { 
    if( a[i] <= a[j] )  
    b[index++] = a[i++] ; 
    else 
    b[index++] = a[j++] ; 
    } 
    while (i<=mid)  
    b[index++] = a[i++] ;  
    while (j<=high)  
    b[index++] = a[j++] ; 

    for(index=low; index<=high; index++) 
    a[index] = b[index]; 

    //free(b);
    }

    void mergesort(int a[],int low,int high)
    {
    int mid;
    if(low<high)
    {
     mid=(low+high)/2;
     mergesort(a,low,mid);
     mergesort(a,mid+1,high);
     merge(a,low,mid,high);
    } 
    }

    void main()
    {
    int i,n,low,high,j;
    printf("Enter the number of the elements ::");
    scanf("%d",&n);
    int c[n];
    for(i=0;i<n;i++)
    {
    c[i]=rand()%100;
    }

    mergesort(c,0,n-1);

    }

标签: cmergesort

解决方案


推荐阅读