归并排序
来源:互联网 发布:美国网络中立 编辑:程序博客网 时间: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
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 二叉树中相距最远的两个节点之间的距离
- JNI学习积累之一 ---- 常用函数大全
- 阿斯达四大四大
- python对象与json
- java使用android aapt获取APK信息
- 归并排序
- c语言调试
- 百度地图Unknown class BMKMapView in Interface Builder file.
- java 操作excel,jxl加边框,jxl合并单元格,单元格的设置,单元格居中
- 最大流(刚开始接触的总结)
- Longest Substring Without Repeating Characters 最长不重复子串 @LeetCode
- Android各国语言Values文件夹命名规则
- Version提交出现remains in conflict错误解决办法
- 游戏资源打包