C++模板实现归并排序
来源:互联网 发布:乐乎城市青年社区租房 编辑:程序博客网 时间:2024/06/04 19:35
归并排序的思想是将一个大的序列先进行二分法划分,直到划分到每个子序列只包含一个元素为止. 然后对序列进行依次合并,在合并的过程中实现排序.归并排序是一种典型的外部排序算法,需要额外的辅助空间来完成算法.
算法分析:
1.稳定
2.时间复杂度: O(nlog(n))
3.需要额外辅助空间来实现排序
//Mergesort//1. Stable//2. Time complex O(nlog(n))//3. Need addition space's help (tempArray)//4. In one time merge sort, when low>=high, stoptemplate <typename T, unsigned int size>void Sort<T, size>::mergeSort(T* const sortArray, int low, int high){ if (low >= high) { } else { int mid = (low + high) / 2; mergeSort(sortArray, low, mid); mergeSort(sortArray, mid + 1, high); merge(sortArray, low, high); } return;}template <typename T, unsigned int size>void Sort<T, size>::merge(T* const sortArray, int low, int high){ T* tempArray = new T[high-low+1]; int mid = (low + high) / 2; int i = low; int j = mid + 1; int tempArrayIndex = 0; while ((i <= mid) && (j <= high)) { loopTimes++; if (sortArray[i] <= sortArray[j]) { tempArray[tempArrayIndex] = sortArray[i]; i++; tempArrayIndex++; } else { tempArray[tempArrayIndex] = sortArray[j]; j++; tempArrayIndex++; } } if (i > mid) { while (j <= high) { loopTimes++; tempArray[tempArrayIndex] = sortArray[j]; j++; tempArrayIndex++; } } else if (j > high) { while (i <= mid) { loopTimes++; tempArray[tempArrayIndex] = sortArray[i]; i++; tempArrayIndex++; } } //tempArrayIndex = 0; //for (int i = low; i <= high; i++) //{ // sortArray[i] = tempArray[tempArrayIndex]; // tempArrayIndex++; //} memset(&sortArray[low], 0, sizeof(T) * (high-low+1)); memcpy(&sortArray[low], tempArray, sizeof(T) * (high-low+1)); delete[] tempArray; tempArray = NULL; return;}
0 0
- c/c++之模板方法实现归并排序
- c++模板实现归并排序
- C++模板实现归并排序
- 归并排序 c语言实现
- 归并排序C语言实现
- 归并排序C语言实现
- 归并排序--C语言实现
- 归并排序C语言实现
- 归并排序--c语言实现
- C语言实现归并排序
- 归并排序 --C语言实现
- 排序(6)---------归并排序(C语言实现)
- 排序算法(C实现)-------- 归并排序
- 排序算法C++&&Python实现---归并排序
- 排序算法C++&&Python实现---归并排序
- c++ 模板实现 -- 直接插入排序和归并排序
- 归并排序模板
- C++归并排序模板
- C++命名规则------文件
- 终端命令
- webpack入门篇
- 关于解决DockManager如何停靠在其他布局控件问题
- 大数据处理题型分析
- C++模板实现归并排序
- JAVA-练习MyShopping查询商品价格
- 最佳的MongoDB客户端管理工具
- 设计模式之观察者模式
- 单例模式-单例模式调用普通类,普通类也可以实现单例模式
- 浏览器重绘和重排
- JAVA-练习Shopping_settlement升级购物结算
- Retrofit2+Okhttp3+Rxjava2通过SOAP协议请求WebService
- 题目1198:a+b 九度OJ