归并排序

来源:互联网 发布:美国网络中立 编辑:程序博客网 时间:2024/06/11 07:12

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

时间复杂度: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
原创粉丝点击