归并排序
来源:互联网 发布:简单的java代码 编辑:程序博客网 时间:2024/06/06 12:32
采用分治的思想 以O(NlogN)最坏的情形运行时间运行
如果对merge的每个递归调用都采用局部声明一个临时数组,那么在任一时刻就可能有logN个临时数组处在活动期
代码如下:
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 template <typename Comparable> 5 void mergeSort(vector<Comparable> & a) 6 { 7 vector<Comparable> tmpArray(a.size()); 8 mergeSort(a,tmpArray,0,a.size()-1); 9 }10 template <typename Comparable>11 void mergeSort(vector<Comparable> & a,vector<Comparable> & tmpArray,int left,int right)12 {13 if(left<right)14 {15 int center = (left+right)/2;16 mergeSort(a,tmpArray,left,center);17 mergeSort(a,tmpArray,center+1,right);18 merge(a,tmpArray,left,center+1,right);19 }20 }21 template <typename Comparable>22 void merge(vector<Comparable> & a,vector<Comparable> & tmpArray,int leftPos,int rightPos,int rightEnd)23 {24 int leftEnd = rightPos-1;25 int tmpPos = leftPos;26 int numElements = rightEnd - leftPos + 1;27 28 while(leftPos <= leftEnd && rightPos <= rightEnd)29 if(a[leftPos] <= a[rightPos])30 tmpArray[tmpPos++] = a[leftPos++];31 else32 tmpArray[tmpPos++] = a[rightPos++];33 34 while(leftPos <= leftEnd)35 tmpArray[tmpPos++] = a[leftPos++];36 while(rightPos <= rightEnd)37 tmpArray[tmpPos++] = a[rightPos++];38 39 for(int i=0;i<numElements;i++,rightEnd--)40 a[rightEnd] = tmpArray[rightEnd];41 }42 int main()43 {44 vector<int> ivec;45 ivec.push_back(1);46 ivec.push_back(9);47 ivec.push_back(2);48 ivec.push_back(10);49 ivec.push_back(3);50 ivec.push_back(11);51 ivec.push_back(4);52 ivec.push_back(12);53 ivec.push_back(5);54 ivec.push_back(13);55 ivec.push_back(6);56 ivec.push_back(14);57 ivec.push_back(7);58 ivec.push_back(15);59 ivec.push_back(8);60 ivec.push_back(16);61 mergeSort(ivec);62 for(int j = 0;j<ivec.size();j++)63 cout<<ivec[j]<<endl;64 return 0;65 }
运行结果:
阅读全文
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 【POJ1160】【四边形优化DP】Post Office
- UVA 839 Not So Mobile 【递归+树】
- 快速排序
- leetcode-303. Range Sum Query
- POJ3977_Subset_折半搜索
- 归并排序
- Java基础 求最大值
- hdu-3045 Picnic Cows
- 堆排序
- fasterrcnn训练自己的数据
- 希尔排序
- leetcode 582.Kill Process
- POJ 1254 Hansel and Grethel 笔记
- 获取本机地址信息,遇到小问题...有待解决