归并排序
来源:互联网 发布:在线测试网络丢包率 编辑:程序博客网 时间:2024/05/21 06:30
1.归并排序的概念
- 将待排序元素分成两个区间,用递归思想将两个区间进行排序。
- 将 两个排好的有序区间的元素进行合并。
2.归并排序的思想
- 分治思想
- 递归思想(区间的不断缩小)
3.归并排序的的实现
3.1先从简单的合并开始
//将有序数组a[]和b[]合并到c[]中 void MemeryArray(int a[], int n, int b[], int m, int c[]) { int i, j, k; i = j = k = 0; while (i < n && j < m) { if (a[i] < b[j]) c[k++] = a[i++]; else c[k++] = b[j++]; } while (i < n) c[k++] = a[i++]; while (j < m) c[k++] = b[j++]; }
3.2 类比上面,然后已经分出来的区间进行合并
void mergearray(int a[], int first, int mid, int last, int temp[]) { int i = first, j = mid + 1; int m = mid, n = last; int k = 0; while (i <= m && j <= n) { if (a[i] <= a[j]) temp[k++] = a[i++]; else temp[k++] = a[j++]; } while (i <= m) temp[k++] = a[i++]; while (j <= n) temp[k++] = a[j++]; for (i = 0; i < k; i++) a[first + i] = temp[i]; }
3.3 对整个待排序元素进行分割,然后合并。
void mergesort(int a[], int first, int last, int temp[]) { if (first < last) { int mid = (first + last) / 2; mergesort(a, first, mid, temp); //左边有序 mergesort(a, mid + 1, last, temp); //右边有序 mergearray(a, first, mid, last, temp); //再将二个有序数列合并 } }
3.4 主函数,以及待排序元素的输入解决
bool MergeSort(int a[], int n) { int *p = new int[n]; //int *p =(int *) malloc(sizeof(int)*n); if (p == NULL) return false; mergesort(a, 0, n - 1, p); delete[] p; return true; }
参考
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- UIPasteboard的使用
- 贪吃蛇的java代码分析(一)
- ConditionExpression's ConditionOperator For Datetime
- MongoDB番外篇
- leetcode Construct Binary Tree from Inorder and Postorder Traversal
- 归并排序
- 基于HDFS的SparkStreaming案例实战
- 监控系统cat安装和配置demo ubuntu 14.04
- SQL Server 2016新特性: 对JSON的支持
- react学习笔记
- non-zero exit value 3 bug 修复
- 初等因子
- tomcat:The APR based Apache Tomcat Native library which allows optimal performance in production问题解决
- iOS UIApplication和程序启动原理