c - 合并排序的实现不起作用?

标签 c mergesort

运行代码后我的数组没有排序。怎么了?

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

我已经尝试了很长时间,但都是徒劳的。

   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];
}



  }

最佳答案

您的 while 条件已关闭,需要清空数组 while (j<i)永远不会是真的。

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

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

关于c - 合并排序的实现不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27751620/

相关文章:

javascript - 使用 mergesort 计算反转 - javascript

visual-c++ - 合并排序C++无效[歧义错误]

c++ - 单链表 C++ 上的归并排序

c# - C 中的 allocVector() 和 System.AccessViolationException : Attempted to read or write protected memory?

c - 使用 INADDR_LOOPBACK 的环回示例不起作用

c - procs、fork() 和互斥体

C:运行系统命令并获取输出?

c - 如何使用合并排序删除重复项?

c - 通过绕道减少非决定论?

java - 合并两个排序数组时,使用数组还是队列更好?