归并排序

#include <stdio.h>
#include<stdlib.h>

typedef int ElementType;
void MSort(ElementType A[],ElementType TmpArry[],int Left,int Right);
void MergeSort(ElementType A[],int N);
void Merge(ElementType A[],ElementType[],int Lpos,int Rpos,int RightEnd);

int main(void)                                                         //归并排序
{
    int a[10] = {12,33,45,84,6,3,49,51,2,};
    int i;

    MergeSort(a,10);


    for(i = 0; i < 10; i++)
        printf("%-4d",a[i]);

    printf("\nHello World!\n");
    return 0;
}

void MSort(ElementType A[],ElementType TmpArry[],int Left,int Right)    //递归排序
{
    int Center;

    if(Left < Right)                                    //请数列分成两部分,分别排序
    {
        Center = (Left + Right) / 2;
        MSort(A,TmpArry,Left,Center);
        MSort(A,TmpArry,Center + 1,Right);
        Merge(A,TmpArry,Left,Center + 1,Right);         //合并两部分
    }
}

void MergeSort(ElementType A[],int N)               //排序驱动程序
{
    ElementType *TmpArray;

    TmpArray = (ElementType*)malloc(N * sizeof(ElementType));   //分配第三个数列,用来合并
    if(TmpArray != NULL)
    {
        MSort(A,TmpArray,0,N - 1);
        free(TmpArray);
    }
    else
        printf("No space for tmp array\n");
}

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值