归并排序

采用分治的思想  以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         else
32             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 } 

运行结果:

posted @ 2012-09-27 19:34  xingoo  阅读(336)  评论(0编辑  收藏  举报