编辑代码

#include <stdio.h>

void merge(int a[],int temp[],int L,int R,int RightEnd);

/*
  params:
    int a[]:待排序的数组
    int tempArray[]:临时数组
    L:左边起始位置
    R:右边起始位置
    RightEnd:右边终点位置
*/
void merge(int a[],int tempArray[],int L,int R,int RightEnd){
    int i,temp,LeftEnd,NumElemments;

    //左边终点位置,假设左右列挨着
    LeftEnd = R - 1;
    //存放结果的数组的初始位置
    temp = L;
    //记录元素个数
    NumElemments = RightEnd - L + 1;
    while(L <= LeftEnd && R <= RightEnd){
        if(a[L] >= a[R]){
            tempArray[temp] = a[R];
            R++;
            temp++;
        }else{
            tempArray[temp] = a[L];
            L++;
            temp++;
        }
    }
    //直接复制左边剩下的
    while(L <= LeftEnd){
        tempArray[temp++] = a[L++];
    }
    //直接复制右边剩下的
    while(R <= RightEnd){
        tempArray[temp++] = a[R++];
    }

    /*把归并后的tempArray倒回a
      从右往左开始,在复制过程中L被更改
      原来的位置丢失,故不能从左往右开始
    */
    for(i = 0;i < NumElemments;i++,RightEnd--){
        a[RightEnd] = tempArray[RightEnd];
    }
    for(i = 0;i < NumElemments;i++){
        printf("%d ",a[i]);
    }
    // for(i = 0;i < NumElemments;i++){
    //     printf("%d ",tempArray[i]);
    // }
}

int main () {
   int a[6] = {34,51,89,16,20,25};
   int tempArray[6];
    printf("排序前的元素为:\n");
    for(int i = 0;i < 6;i++){
        printf("%d ",a[i]);
    }
    printf("\n");
    printf("排序后的元素为:\n");
    merge(a,tempArray,0,3,5);
}