AcWing 787. 归并排序(递归和非递归)
原题链接
简单
作者:
Dilemma0
,
2021-07-17 08:53:13
,
所有人可见
,
阅读 212
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 200010;
int q[N], tmp[N];
void merge_sort(int q[], int l, int r) //递归版
{
if(l >= r) return;
int mid = l + r >> 1;
merge_sort(q, l, mid), merge_sort(q, mid + 1, r);
int i = l, j = mid + 1, k = 0;
while(i <= mid && j <= r)
{
if(q[i] <= q[j]) tmp[k++] = q[i++];
else tmp[k++] = q[j++];
}
while(i <= mid) tmp[k++] = q[i++];
while(j <= r) tmp[k++] = q[j++];
for(i=l, j=0; i<=r; i++, j++) q[i] = tmp[j];
}
//非递归版
void non_merge_sort(int nums[], int n) //使用非递归时,需要将空间开成两倍
{
int step = 1;
while(step < n)
{
int i = 0;
int left, right, lTop, rTop; //设置左右数组边界
while(i < n)
{
left = i;
lTop = i + step - 1;
right = lTop + 1;
if(right + step - 1 > n - 1)
{
rTop = n - 1;
}else{
rTop = right + step - 1;
}
int p = left;
int q = right;
int k = left;
while(p <= lTop && q <= rTop)
{
if(nums[p] <= nums[q])
{
tmp[k++] = nums[p++];
}else{
tmp[k++] = nums[q++];
}
}
while(p <= lTop) tmp[k++] = nums[p++];
while(q <= rTop) tmp[k++] = nums[q++];
for(int j=left; j<=rTop; j++) nums[j] = tmp[j];
i += 2 * step;
}
step = 2 * step;
}
}
int main()
{
int n;
scanf("%d", &n);
for(int i=0; i<n; i++) scanf("%d", &q[i]);
non_merge_sort(q, n);
for(int i=0; i<n; i++) printf("%d ", q[i]);
return 0;
}