二刷
C++ 代码
#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int a[N];
int n;
void merge(int l, int r)
{
//终止
if(l >= r) return ;
int mid = (l + r) >> 1;
// 分治解决
merge(l, mid);
merge(mid + 1, r);
//下面合并子问题
int x = r - l + 1;
int temp[x]; //临时合并函数
int i = l, j = mid + 1, k = 0;
while(i <= mid && j <= r)
{
if(a[j] >= a[i])
{
temp[k++] = a[i++];
}
else temp[k++] = a[j++];
}
while(i <= mid) temp[k++] = a[i++];
while(j <= r) temp[k++] = a[j++];
//将临时数组拷贝回原数组
for(int i = 0, j = l; j <= r; i++, j++)
{
a[j] = temp[i];
}
}
int main()
{
cin >> n;
for(int i = 0; i < n; i ++) cin >> a[i];
merge(0, n - 1);
for(int i = 0; i < n; i ++) cout << a[i] << " ";
return 0;
}