C++模板实现归并排序
2017-04-25 12:38
591 查看
归并排序的思想是将一个大的序列先进行二分法划分,直到划分到每个子序列只包含一个元素为止. 然后对序列进行依次合并,在合并的过程中实现排序.归并排序是一种典型的外部排序算法,需要额外的辅助空间来完成算法.
算法分析:
1.稳定
2.时间复杂度: O(nlog(n))
3.需要额外辅助空间来实现排序
算法分析:
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, stop template <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; }
相关文章推荐
- C++模板实现归并排序
- C++模板实现归并排序
- c++ 模板实现 -- 直接插入排序和归并排序
- C++模板实现归并排序
- c++模板实现归并排序
- C++模板实现归并排序
- c/c++之模板方法实现归并排序
- C++模板实现归并排序
- C++模板实现归并排序
- C++模板实现归并排序
- c++模板的定义和实现
- 用C++模板实现事件模型
- 利用C++模板,代替虚函数,实现类的静态多态性(加入性能测试部分)
- 我用c++实现的模板单链表类.并用一个一元多项式进行测试.
- 采用C++模板技术,实现的分布式哈希存储服务器
- 单件模式的C++模板实现
- C++设计模式:Singleton的模板实现之一
- 使用C++模板实现不需要IDL的RPC【二】
- 单件模式的C++模板实现
- C++模板实现事件处理器中的“通用成员函数指针”的调用(二)