归并排序-nlogn
2016-03-15 19:41
239 查看
//归并排序 void mergeArray(int a[], int first, int mid, int last, int temp[]) //对两个有序数列合并 { int i = first; int j = mid + 1; int m = mid; int n = last; int k = 0; //每次把两个数列中较小的值存在temp中 while(i <= m && j <= n) { if(a[i]<= a[j]) { temp[k++] = a[i++]; } else { temp[k++] = a[j++]; } } //哪一个数列先完成拷贝就把另一个数列的剩余的值存在temp中 while(i <= m) { temp[k++] = a[i++]; } while(j <= n) { temp[k++] = a[j++]; } //把temp中的值拷贝到a中 for(int i = 0; i < k; ++i) { a[first+i] = temp[i]; } } void mergeSort(int a[], int first, int last, int temp[]) { if(first < last) { int mid = (last + first)/2; //注意用加号,不是减号, //将数组划分成由单个数组成的数列,则就可看成是每个数列都是有序的,可以用mergeArray函数了 mergeSort(a, first, mid, temp); mergeSort(a, mid+1, last, temp); mergeArray(a, first, mid, last, temp); } } bool MergeSort(int a[], int n) { int *p = new int ; if(p == NULL) { return false; } else { mergeSort(a, 0, n-1, p); delete[] p; return true; } }
相关文章推荐
- 我的C语言之路2
- 最短路之dijkstra算法
- 2015搜狐在线笔试题(内存泄露问题)(转)
- 我在部署docker的时候遇到的坑
- RadioButton自定义样式及点击事件全解析
- 第二周 项目四
- 51nod--1242 斐波那契数列第N项 (矩阵乘法优化)
- RAM之程序运行时数据和代码加载
- 最长上升子序列
- Cannot reload AVD list
- 1.ARM基础概念及芯片平台
- Python正则表达式,re模块
- 基于Face++实现的人脸检测(年龄检测)Android程序
- 如何居中一个浮动元素?
- cocos2d-x 关于tilemap滚动时黑线闪动的问题
- OpenGL with PyOpenGL Python and PyGame p.4-Moving the player automatically towards the cube
- ZOJ 3497 Mistwald【矩阵快速幂】【图论】
- Android设计模式之代理模式 Proxy
- 记录合法的最长的串
- 图论面试题