首页 > 编程语言 > 详细

归并排序

时间:2017-07-30 00:00:23      阅读:266      评论:0      收藏:0      [点我收藏+]

合并2个已排序的表

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

 

归并排序

原文:http://www.cnblogs.com/m2492565210/p/7257885.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!