视频链接:https://www.bilibili.com/video/av9982752?from=search&seid=12418703498405255943
参考代码:
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn = 100005;
int n;
int a[maxn];
void merge(int L, int M, int R)
{
const int Sizeof_Left = M - L + 1;
const int Sizeof_Right = R - M;
int *left=new int[Sizeof_Left];
int *right=new int [Sizeof_Right];
for (int i = L; i <= M; i++)
left[i - L] = a[i];
for (int i = M + 1; i <= R; i++)
right[i - M - 1] = a[i];
int i = 0;
int j = 0;
int k = L;
while (i < Sizeof_Left&&j < Sizeof_Right)
{
if (left[i] < right[j])
{
a[k] = left[i];
i++;
k++;
}
else
{
a[k] = right[j];
j++;
k++;
}
}
while (i < Sizeof_Left) a[k++] = left[i++];
while (j < Sizeof_Right) a[k++] = right[j++];
}
void mergesort(int L, int R)
{
if (L == R) return;
int M = (L + R) /2;
mergesort(L, M);
mergesort(M + 1, R);
merge(L, M, R);
}
int main()
{
printf("输入数组大小:
");
cin >> n;
printf("输入数组元素:
");
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
mergesort(0, n - 1);
printf("归并排序后结果:
");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("
");
return 0;
}