简体   繁体   English

实施合并排序不起作用?

[英]Implementation of merge sort not working?

My array is not sorted after running the code. 运行代码后,我的数组未排序。 What's wrong? 怎么了?

Result: 3,8,9,6,11,3,22,95. 结果:3,8,9,6,11,3,22,95。

I have tried long but all in vain. 我已经尝试了很长时间,但都没有成功。

   int main(int argc, char const *argv[]){
        int i;
        int my[]={3,11,19,22,8,9,13,95};
        msort(my,0,7);

        for(i=0;i<8;i++){
           printf("%d,",my[i]);
          }
       return 0;
 }

 int msort(int *ar,int low, int high){
       int mid;
       if(low<high){
          mid = (low+high)/2;

        msort(ar,low,mid);
        msort(ar,mid+1,high);
        merge(ar,low,mid,high);
     }
  }


int merge(int *ar,int low,int mid, int high){
//int ar[]={3,11,19,22};
//int ar2[]={8,9,13,95};
int temp[8];

int i,j,index,k;
k=0;
index=low;
i=low;
j=mid+1;
while(i<=mid && j<=high){
    if(ar[i]<ar[j]){
        temp[index++] = ar[i];
        i++;
    }else{
        temp[index++] = ar[j];
        j++;
    }
}
while(i<j){
    temp[index++] = ar[i];
    i++;

}
while(j<i){
    temp[index++] = ar[j];

    j++;
}

  //here i am updating my array with temp;

for(k=low;k<high;k++){
    ar[k]=temp[k];
}



  }

your while conditions are off, need to empty the arrays while (j<i) is never true. 当while条件关闭时,需要while (j<i)永远不为真时清空数组。

while (i <= mid) { 
    temp[index++] = ar[i];
    i++;
}

while (j <= high) {
    temp[index++] = ar[j];
    j++;
}
int merge(int *ar,int low,int mid, int high){
    int temp[8];

    int i,j,index,k;
    k=0;
    index=0;//temp's index start 0;
    i=low;
    j=mid+1;
    while(i<=mid && j<=high){
        if(ar[i]<ar[j]){
            temp[index++] = ar[i];
            i++;
        }else{
            temp[index++] = ar[j];
            j++;
        }
    }
    while(i<=mid){
        temp[index++] = ar[i];
        i++;
    }
    while(j<=high){
        temp[index++] = ar[j];
        j++;
    }

    for(k=low, index=0;k<=high;k++){//k include high
        ar[k]=temp[index++];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM