Merge Sort

作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4030019.html

算法导论第二章的归并排序,注意在merge步骤时,要开辟临时数组保存两个数组排序候的结果,然后在把临时数组逐个导入待排序数组中。

代码如下:

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <vector>
 4 using namespace std;
 5 void merge(vector<int> &arr, int s1, int e1,  int e2)
 6 {
 7     int p1 = s1;
 8     int p2 = e1+1;
 9     vector<int> tmp;
10     while( p1 <= e1 && p2 <= e2 )
11     {
12         if( arr[p1] < arr[p2] )
13         {
14             tmp.push_back(arr[p1]);
15             p1++;
16         }
17         else
18         {
19             tmp.push_back(arr[p2]);
20             p2++;
21         }
22     }
23     while( p2 <= e2 )
24     {
25         tmp.push_back(arr[p2]);
26         p2++;
27     }
28     while(p1 <= e1)
29     {
30         tmp.push_back(arr[p1]);
31         p1++;
32     }
33     int j = 0;
34     for( int i = s1 ; i <= e2 ; i++ )
35     {
36         arr[i] = tmp[j++];
37     }
38 }
39 
40 void mergesort(vector<int> &arr, int s, int e)
41 {
42     if( s < e )
43     {
44         int mid = (s+e)/2;
45         mergesort(arr, s, mid);
46         mergesort(arr, mid+1,e);
47         merge(arr, s, mid, e);
48     }
49 }
50 
51 int main(int argc, char *argv[])
52 {
53     vector<int> a; 
54     int n;
55     cin>>n;
56     for( int i = 0 ; i < n ;i++  )
57     {
58         int tmp;
59         cin>>tmp;
60         a.push_back(tmp);
61     }
62     mergesort(a, 0, n-1);
63     for( int i = 0 ; i < n ; i++ )
64     {
65         cout<<a[i]<<" ";
66     }
67     cout<<endl;
68 }
View Code

 

posted @ 2014-10-16 23:58  jostree  阅读(139)  评论(0编辑  收藏  举报