# MergeSort（归并排序）原理及C++代码实现

0
12

```1 void MergeSort(int * const begin, int * const end) {
2     if (begin + 1 >= end)
3         return ;
4     int m = (end - begin) / 2;
5     MergeSort(begin, begin + m);
6     MergeSort(begin + m, end);
7     Merge(begin, begin + m, end);
8 }```
``` 1 //不使用哨兵的版本，需判断边界条件
2 void Merge(int * const first, int * const mid, int * const last) {
3     vector<int> left(first, mid);
4     vector<int> right(mid, last);
5
6     int i = 0, j = 0, k = 0;
7     while (i != left.size() && j != right.size()) {
8         if (left[i] <= right[j]) {
9             *(first + k) = left[i++];
10         } else {
11             *(first + k) = right[j++];
12         }
13         ++k;
14     }
15     while (i != left.size()) {
16         *(first + k) = left[i++];
17         ++k;
18     }
19     while (j != right.size()) {
20         *(first + k) = right[j++];
21         ++k;
22     }
23 }```
``` 1 //使用哨兵来简化代码
2 void Merge(int * const first, int * const mid, int * const last) {
3     vector<int> left(first, mid);
4     vector<int> right(mid, last);
5     left.push_back(INT_MAX);       //哨兵INT_MAX必须总是比较中的较大者
6     right.push_back(INT_MAX);      //即待排序的值必须比INT_MAX小
7
8     int i = 0, j = 0;
9     for (int k = 0; k < last - first; ++k) {
10         if (left[i] <= right[j]) {
11             *(first + k) = left[i++];
12         } else {
13             *(first + k) = right[j++];
14         }
15     }
16 }```

<

0