归并排序-非递归版
2016-04-26 23:32
357 查看
计算机算法设计与分析第四版[王]
2.7合并排序
此方法是直接的使用归并排序是思想,按照分段大小,两端两端的合并即可。
2.7合并排序
#include<iostream> using namespace std; template<class type> void MergePass(type x[], type y[], int s, int n) { int i = 0;//合并大小为s的相邻2段子数组 while (i <= n - 2 * s) { Merge(x, y, i, i + s - 1, i + 2 * s - 1); i = i + 2 * s; }//剩下的元素个数少于2s if (i + s < n) Merge(x, y, i, i + s - 1, n - 1);;//剩下的长度大于一个归并段 else for (int j = i;j <= n - 1;j++) y[j] = x[j];//剩下的长度小于一个归并段 } template<class type> void Merge(type c[], type d[], int l, int m, int r) { //合并c[1:m] 和c[m+1:r]到d[l:r] int i = l, j = m + 1, k = l; while ((i <= m) && (j <= r)) { if (c[i] <= c[j]) d[k++] = c[i++]; else d[k++] = c[j++]; } if (i <= m)for (int q = i;q <= m;q++) d[k++] = c[q]; else for (int q = j;q <= r;q++) d[k++] = c[q]; } template<class type> void MergeSort(type a[], int n) { type *b = new type ; int s = 1;//初始合并段宽度 while (s < n) { MergePass(a, b, s, n);//合并到数组b s += s; MergePass(b, a, s, n);//合并的数组a s += s; } } int main() { int a[] = { 1000,55,654,12,333,66666,2,548,22,996,24,11,5 }; MergeSort(a, 13); for (int i = 0;i < 2;i++) { cout << a[i] << endl; } }
此方法是直接的使用归并排序是思想,按照分段大小,两端两端的合并即可。
相关文章推荐
- java实现归并排序算法
- C++实现八个常用的排序算法:插入排序、冒泡排序、选择排序、希尔排序等
- C++实现自底向上的归并排序算法
- C++实现自顶向下的归并排序算法
- Java实现八个常用的排序算法:插入排序、冒泡排序、选择排序、希尔排序等
- Java排序算法总结之归并排序
- C++归并排序算法实例
- Javascript排序算法之合并排序(归并排序)的2个例子
- 归并排序的递归实现与非递归实现代码
- java二路归并排序示例分享
- java实现归并排序算法
- 归并排序的实现代码与思路
- leetcode 虐我篇之(二) Two Sum
- In-place Merge Sort 原地并归排序
- 使用Java完成《算法导论》习题2.3-2
- 插入排序移动次数
- 归并排序 with Python
- 归并排序-逆序对的求解
- 排序算法的复杂度和稳定性
- 用python实现归并排序