归并排序
来源:互联网 发布:蓝光原盘播放软件 编辑:程序博客网 时间: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; }
阅读全文
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- tomcat 从浏览器进入指定目录
- 通信原理Ch1
- 机器学习学习笔记——Logistic Regression
- SQL truncate 、delete与drop区别
- 识别有效的IP地址和掩码并进行分类
- 归并排序
- repo upload 提示 no branches ready for upload
- POJ 1740[A New Stone Game] 题解
- Unity Shader ——人物穿越效果
- Python学习笔记-0
- JAVA多线程基础知识复习二
- opencv 对图像处理的一些函数
- 安卓布局之表格布局(TableLayout)
- ubuntu16.04 sudo 出现unable to resolve host 解决方法