Ubuntu给我错误的输出

时间:2018-08-16 07:54:28

标签: c algorithm mergesort

我面临一个非常不寻常的问题。这是我使用合并排序制作的程序,用于打印最大重复次数的数字。

#include<stdio.h>
int n;
int merge(int a[],int low,int mid,int high){
    int i=low,j=mid+1,c[n],k=low;
    while((i<=mid) && (j<=high)){
        if(a[i]<=a[j]){
            c[k]=a[i];
            i=i+1;
            k=k+1;
        }

        else{
            c[k]=a[j];
            k=k+1;
            j=j+1;
        }
    }

    while(i<=mid){
        c[k]=a[i];
        i=i+1;
        k=k+1;
    }

    while(j<=high){
        c[k]=a[j];
        j=j+1;
        k=k+1;
    }

    for(i=low;i<=high;i++){
        a[i]=c[i];
    }
    return 0;
}


int mergeSort(int a[],int low,int high){
    int mid=0;
    if(low<high){
        mid=(low+high)/2;

        mergeSort(a,low,mid);
        mergeSort(a,mid+1,high);

        merge(a,low,mid,high);
    }
    return 0;
}

int main(){
    int i,a[n];
    printf("\nEnter the size of array:\n");
    scanf("%d",&n);
    printf("\nEnter the elements:\n");
    for(i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    mergeSort(a,0,n-1);
    printf("\nThe array after merge sort is-\n");
    for(i=0;i<n;i++){
        printf("%d ",a[i]);
    }
    i=0;
    int j=i+1,count=1,maxCount=1,flag=0,f=0;
    int arr1[n],arr2[n];
    //printf("%d ",n);
    while(i<(n-1) && j<n){
        j=i+1;
        while(a[i]==a[j]){
            count++;
            j++;
        }
        //printf("%d %d %d %d %d\n",count,a[i],a[j],i,j);
        if(count>1 && count>=maxCount){
            //printf("%d repeated %d times",a[i],count);
            arr1[f]=count;
            arr2[f]=a[i];
            flag=1;
            f++;
            maxCount=count;
        }
        i=j;
        count=1;
    }
    for(i=0;i<f;i++){
        if(arr1[i]==maxCount)
            printf("\n%d repeated %d times\n",arr2[i],arr1[i]);
    }
    if(flag==0){
        printf("\nNo repetitions\n");
    }
    return 0;
}

When running this program on Ubuntu, I'm getting this output-

When running the exact same program on GeeksforGeeks IDE with the same inputs[But on hackerrank IDE for the same input I'm getting the right output.] 2,我得到相同的错误输出-

请说明为什么同一程序只能在hackerrank IDE上运行。是因为时间复杂吗?根据我的说法,这是nlogn并已优化。还是因为空间复杂?请解释。谢谢。

1 个答案:

答案 0 :(得分:2)

程序中至少有一个错误:

int i,a[n];
printf("\nEnter the size of array:\n");
scanf("%d",&n);

创建数组a时,尚未设置n

n(具有extern存储空间的变量)被初始化为零,因此您的数组大小将为零。由于您随后将项目放入其中,因此您正在将数据存储在其分配的空间之外,这是未定义的行为。任何事情都可能发生,并且在不同平台上可能会有所不同。