AcWing 787. 归并排序
原题链接
简单
作者:
Value
,
2020-05-27 10:13:56
,
所有人可见
,
阅读 449
#include <iostream>
using namespace std;
const int N = 1E5 + 10;
int a[N], backup[N];
void merge_sort(int l, int r){
if(l == r) return ;
int mid = l + r >> 1;
merge_sort(l, mid);
merge_sort(mid + 1, r);
int i = l, j = mid + 1, k = 0;
while(i <= mid && j <= r){
if(a[i] <= a[j]) backup[k ++ ] = a[i ++ ];
else backup[k ++ ] = a[j ++ ];
}
while(i <= mid) backup[k ++ ] = a[i ++ ];
while(j <= r) backup[k ++ ] = a[j ++ ];
k = 0;
for(i = l; i <= r; i ++ ) a[i] = backup[k ++ ];
}
int main(){
int n; cin >> n;
for(int i = 0; i < n; i ++ ) cin >> a[i];
merge_sort(0, n - 1);
for(int i = 0; i < n; i ++ ) cout << a[i] << " ";
}