归并排序

来源:互联网 发布:蓝光原盘播放软件 编辑:程序博客网 时间:2024/06/05 05:42

排序算法之归并排序

归并排序采用分治法。



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

最优时间复杂度:O(N)

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

空间复杂度:O(N)



一个归并排序的例子:对一个随机点的链表进行排序

#include<stdio.h>#include<stdlib.h>#include<string.h>void Merger(int a[],int nlow,int nhigh){int begin1,end1;int begin2,end2;int i;int *ptemp=NULL; //临时数组begin1=nlow;end1=(nhigh+nlow)/2;begin2=end1+1;end2=nhigh;//为临时数组申请空间并初始化ptemp=(int *)malloc(sizeof(int)*(nhigh-nlow+1));memset(ptemp,0,sizeof(int)*(nhigh-nlow+1));i=0;while (begin1<=end1 &&begin2<=end2){if(a[begin1]<a[begin2]){ptemp[i]=a[begin1];begin1++;}else{ptemp[i]=a[begin2];begin2++;}i++;} //剩余元素加入到临时数组while (begin1<=end1){ptemp[i]=a[begin1];begin1++;i++;}while (begin2<=end2){ptemp[i]=a[begin2];begin2++;i++;}//放回到原数组for(i=0;i<nhigh-nlow+1;i++){a[nlow+i]=ptemp[i];}//释放临时数组空间free(ptemp);ptemp=NULL;}void MergerSort(int  a[],int nlow,int nhigh){int mid;if(a==NULL ||nlow>=nhigh) return ;mid=(nlow+nhigh)/2;//拆分MergerSort(a,nlow,mid);MergerSort(a,mid+1,nhigh);//合并Merger(a,nlow,nhigh);}int main(){int i;int a[]={5,3,8,7,9,22,11,47,6,9,23}; int len=sizeof(a)/sizeof(a[0]);MergerSort(a,0,len-1);for(i=0;i<len;i++){printf("%d ",a[i]);}system("pause");return 0; }