码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序

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

标签:int   logs   rpo   bsp   pre   []   log   code   归并   

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

 

归并排序

标签:int   logs   rpo   bsp   pre   []   log   code   归并   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!