先递归为多个小部分再进行排序
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int a[N], tem[N];
void merge_sort(int a[], int l, int r)
{
if (l >= r) return;
int mid = l + r >> 1;
merge_sort(a, l, mid), merge_sort(a, mid + 1, r); //递归分为两部分
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r) //取两部分中最小的值放入另一个数列
if (a[i] <= a[j]) tem[k ++] = a[i ++];
else tem[k ++] = a[j ++];
while (i <= mid) tem[k ++] = a[i ++];
while (j <= r) tem[k ++] = a[j ++];
for (i = l, j = 0;i <= r;i ++, j ++) a[i] = tem[j];
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 0;i < n;i ++) scanf("%d", &a[i]);
merge_sort(a, 0, n - 1);
for (int i = 0;i < n;i ++) printf("%d ", a[i]);
return 0;
}
标签:sort,归并,int,mid,merge,排序
From: https://www.cnblogs.com/acing/p/18550255