AcWing 787. 归并排序
原题链接
简单
作者:
时过境迁
,
2020-10-16 17:48:05
,
所有人可见
,
阅读 305
#include <cstdio>
#include <iostream>
using namespace std;
int arr[100004], helper[100004];
int n;
void merge(int arr[], int l, int mid, int r)
{
for(int i = l; i <= r; ++i)
{
helper[i] = arr[i];
}
int i = l, j = mid + 1, current = l;
while(i <= mid && j <= r)
{
if(helper[i] <= helper[j])
{
arr[current++] = helper[i++];
}
else
{
arr[current++] = helper[j++];
}
}
while(i <= mid)
{
arr[current++] = helper[i++];
}
}
void merge_sort(int arr[], int l, int r)
{
if(l >= r)
{
return ;
}
int mid = l + ((r-l)>>1);
merge_sort(arr, l, mid);
merge_sort(arr, mid+1, r);
merge(arr, l, mid, r);
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; ++i)
{
scanf("%d", &arr[i]);
}
merge_sort(arr, 0, n-1);
for(int i = 0; i < n; ++i)
{
printf("%d ", arr[i]);
}
return 0;
}