归并排序

并归运用的思想:分治 ,通过递归把分成各个小部分逐个解决,最后合并解决大问题;

时间复杂度:O(N*logN)

空间复杂度:O(logN)需要一个与排序一样大的临时数组空间,拷贝到排序数组,若数据很大,还是很影响时间的;

场景:主要用于外存排序

代码:

#include<stdio.h>
#include<malloc.h>
/*
Lpos = start of left half ;     Rpos = start of right half ;
*/
void Merge(int a[] , int TmpArray[] ,int Lpos , int Rpos , int RightEnd )
{
    int i , LeftEnd , Num , TmpPos ;
    LeftEnd = Rpos -1 ;
    TmpPos = Lpos ;
    Num = 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 ) //copy rest of first half
    {
        TmpArray[TmpPos++] = a[Lpos++];
    }

    while(Rpos <= RightEnd ) //copy rest of second half
    {
        TmpArray[TmpPos++] = a[Rpos++];
    }

    //copy TmpArray back to a[]
    for(i = 0 ; i < Num ; i++ , RightEnd-- )
        a[RightEnd] = TmpArray[RightEnd];
   
}
void Msort(int a[] , int 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 MergerSort(int a[] ,int n)
{
    int *TmpArray ;
    TmpArray = (int *)malloc(sizeof(int)*n);
    if (TmpArray != NULL)
    {
        Msort(a,TmpArray,0,n-1);
        printf("Aready alloc space for Temp array! \n");
        free(TmpArray) ; //释放掉临时数组
    }
    else
    {
        printf("No space for temp array! \n");
    }
}
int main()
{
 int a[] = {9,7,54,3,1};
 int i , len = sizeof(a)/sizeof(int);
 MergerSort( a, len ); //建立起临时数组,并调用归并函数
 printf("MergerSort  is done ! \n");
 for(i=0 ; i<len ;i++)
    printf("%d \t" ,a[i]);

    return 0;
}


结果:
Aready alloc space for Temp array!
MergerSort  is done !
1       3       7       9       54
Process returned 0 (0x0)   execution time : 0.031 s
Press any key to continue.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值