归并排序
来源:互联网 发布:企业域名和价格 编辑:程序博客网 时间:2024/05/01 00:25
/* * name : merge sort * author : sangoly * O(nlgn) * S(n) * date : 2014/4/15 */#include <iostream>#include <cstdlib>#include <limits>using namespace std;void merge(int a[], int start, int middle, int end){ int max = numeric_limits<int>::max(); int tempArray1[middle-start+2];//include the start to middle int tempArray2[end-middle+1];//include the middle+1 to end for (int i=0; i<middle-start+1; i++) tempArray1[i] = a[start+i]; tempArray1[middle-start+1] = max;//As the soldier for (int i=0; i<end-middle; i++) tempArray2[i] = a[middle+1+i]; tempArray2[end-middle] = max;//As the soldier int index1 = 0; int index2 = 0; for (int k=start; k<=end; k++) a[k] = tempArray1[index1] > tempArray2[index2] ? (tempArray2[index2++]) : (tempArray1[index1++]);}void merge_sort(int a[], int start, int end){ if (start >= end) return; int middle = (start+end)/2; merge_sort(a, start, middle); merge_sort(a, middle + 1, end); merge(a, start, middle, end);}int main(int argc, const char **argv) { int a[] = {3, 41, 52, 26, 38, 57, 9, 49}; merge_sort(a, 0, 7); for (int i=0; i<8; i++) cout<<a[i]<<" "; cout<<endl; system("pause"); return 0;}归并排序,利用分治法的思想将一个大问题分解为形式等价的小问题的集合,递归求解。如果在插入到原数组的过程中采用插入排序的算法,也可以达到以常量组的空间复杂度完成此项任务,但这是以时间换空间的一种做法,时间性能上会有一定损耗。
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- GoogleMap入门教程 02
- XML DOM 属性和方法
- phpexcel php导入导出excel表格的简单方法
- 那些 iOS 7 中容易被忽视的新特性总结
- String主要方法及用法
- 归并排序
- 实现复数类中运算符重载(3)
- html5 [2] ~之 音频视频
- 图的最大流-前置推送标签方法
- Ubuntu 12.04下安装sun-java6-jdk/jre
- 状态栏
- XAMPP 中使用SMTP服务
- Length of Last Word
- STL 之replace,replace_if,replace_copy,replace_copy_if