分治思想的归并排序算法

今天看了算法导论上归并排序算法部分,应用了分治思想。将书上的伪代码用C++写了出来。但书中的数组下标都是从1开始而不是我们平时使用的从0开始,所以与书中稍有不同。

代码如下(注释用英语写的,如果写汉语,会有难看下划线,实在不喜欢):

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void merge(int M[], int l, int p, int r)
 5 {
 6     int i, j, k;
 7     int n1 = p - l + 1;
 8     int n2 = r - p;
 9     int L[n1 + 1], R[n2 + 1];
10 
11     i = j = 0;
12     while(i < n1)     //the array passed in is divided into two parts, the left part is put into array L[];
13     {
14  //       L[i] = M[l + i -1];   //when first loop,l=p=0,r=1.so l+i-1 is -1, error
15         L[i] = M[l + i];    //the array index in the book is from 1 instead of 0,so "-1" is not needed
16         ++ i;
17     }
18     while(j < n2)     //the right part is put into array R[]
19     {
20         R[j] = M[p + j + 1];     //different from it in the book, +1 is needed
21         ++ j;
22     }
23     L[n1] = 10000;
24     R[n2] = 10000;
25 
26     i = j = 0;
27     for(k = l; k <= r; ++k)      //merge the array passed in
28     {
29         if (L[i] <= R[j])
30         {
31             M[k] = L[i];
32             ++ i;
33         }
34         else
35         {
36             M[k] = R[j];
37             ++ j;
38         }
39     }
40 }
41 void merge_sort(int M[], int l, int r)
42 {
43     for(int i = 0; i < 8; ++i)
44     cout << M[i] << " ";
45     cout << endl;
46     if(l < r)
47     {
48         int p = (l + r) / 2;
49             cout << "p is:" << p << endl;   // these output will help understand how the array is be decomposed
50         merge_sort(M, l, p);
51             cout << "left p:" << p << endl;
52         merge_sort(M, p + 1, r);
53             cout << "right p:" << p << endl;
54         // these two steps is to decompose the array so that we can use function merge(M,l,p,r) to merge it
55         //when using stack, the scene will be saved, every p will be saved,when it is decomposed to the bottom, each scene will be reappear
56         merge(M, l, p, r);
57     }
58 }
59 
60 int main()
61 {
62     int A[8] = {7,6,1,34,2,5,7,3};
63 
64     merge_sort(A, 0, 7);
65     for(int i = 0; i < 8; ++i)      //output the sorted array
66         cout << A[i] << " ";
67     cout << endl;
68     return 0;
69 }

 

posted @ 2014-04-14 21:29  Cay Chan  阅读(568)  评论(0编辑  收藏  举报