合并2个已排序的表

先将初始数组的两段完成排序后放在新数组中,再拷贝回去,由于采用递归方法处理,所以会将最下面的2个元素的先排序,1个的直接被返回了

这个过程一直重复直到完成

void MSort(ElementType A[], ElementType TmpArray[], int Left, int Right) {
    int center;
    if (Left < Right) {
        center = (Left + Right)/2;
        MSort(A, TmpArray, Left, center);
        MSort(A, TmpArray, center+1, Right);
        Merge(A, TmpArray, Left, center+1, Right);
    }
}

void MergeSort(ELementTYpe A[], int N) {
    ELementTYpe *TmpArray = malloc(N*sizeof(ELementTYpe));
    if (TmpArray != NULL) {
        MSort(A, TmpArray, 0, N-1);
        free(TmpArray);
    }
}

void Merge(ElementType A[]; ElementType TmpArray[]; int Lpos; int Rpos; int RightEnd) {
    int i, LeftEnd, NumElements, TmpPos;
    LeftEnd = Rpos - 1;
    TmpPos = Lpos;
    NumElements = RightEnd - Lpos + 1;

    while (Lpos<=LeftEnd && Rpos<=RightEnd) {
        if (A[Lpos]<=A[Rpos]) {
            TmpArray[TmpPos++] = A[LPos++];
        }
        else {
            TmpArray[TmpPos++] = A[Rpos++]
        }
    }

    while (Lpos <= LeftEnd) {
        TmpArray[TmpPos++] = A[Lpos++];
    }
    while (Rpos <+ RightEnd) {
        TmpArray[TmpPos++] = A[Rpos++];
    }

    for (i=0; i<NumElements; i++,RightEnd--) {
        A[RightEnd] = TmpArray[RightEnd];
    }
}

 

posted on 2017-07-29 23:09  啊哈咧  阅读(113)  评论(0编辑  收藏  举报