实现思想:将待排序元素集合分成大小大致相同的2个子集合,分别对2个子集合进行排序,最终将排好序的子集合合并成为一个有序集合
递归实现:
#include <iostream>
using namespace std;//由大到小先分再和
int a[100], b[100];
template <typename Type>
void Copy(Type* a, Type* b, int l, int r) {
for (; l <= r; l++)
a[l] = b[l];
}
template <typename Type>
void Merge(Type* a, Type* b, int l, int m, int r) {
int i = l, j = m + 1, k = l;
while (i <= m && j <= r) {
if (a[i] < a[j])
b[k++] = a[i++];
else {
b[k++] = a[j++];
}
}
while (i <= m)
b[k++] = a[i++];
while (j <= r)
b[k++] = a[j++];
}
template <typename Type>
void MergeSort(Type* a, int l, int r) {//必须l<r,不然l=r,一直循环
if (l < r) {
int m = l + r >> 1;
MergeSort(a, l, m);
MergeSort(a, m + 1, r);
Merge(a, b, l, m, r);
Copy(a, b, l, r);
}
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
MergeSort(a, 0, n - 1);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
}
非递归:
```cpp
#include <iostream>
using namespace std;//由小到大直接排序合并
int a[100];
template <typename Type>
void Merge(Type* a, Type* b, int l, int m, int r) {//merge的两个区间并不一定等长
int i = l, j = m + 1, k = l;
while (i <= m && j <= r) {
if (a[i] < a[j])
b[k++] = a[i++];
else {
b[k++] = a[j++];
}
}
while (i <= m)
b[k++] = a[i++];
while (j <= r)
b[k++] = a[j++];
}
template <typename Type>
void MergePass(Type* a, Type* b, int s, int n) {//合并规模为S的相邻区间,放到b数组里
int i = 0;
while (i <= n - 2 * s) {//i~i+s-1, i+s~i+2s-1先把所有的规模为S的两组合并 i+2s-1<n
Merge(a, b, i, i + s-1, i + 2 * s - 1);
i += 2 * s;
}
if (i + s < n) {//剩余的说明还有两组,一组S,一组不到S
Merge(a, b, i, i + s - 1, n - 1);
}
else {//就一组不到S了,直接不用管先放进去,后面S越来越大一定能轮到S,小于S或者直接两个S把他包括
for (; i < n; i++)
b[i] = a[i];
}
}
template <typename Type>
void MergeSort(Type* a, int n) { //随着S规模不断乘二,不断合并(进行了排序)相邻的两个S区间
int s=1;
Type* b = new Type[n];
while (s < n) {//至少有两个数
MergePass(a, b, s, n);
s <<= 1;
MergePass(b, a, s, n);
s <<=1;
}
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
MergeSort(a, n);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
}