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

时间:2015-01-03 04:08:39

标签: 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];
}



  }

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

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