归并排序考研版
作者:
春江花月夜ovo
,
2024-09-12 11:37:57
,
所有人可见
,
阅读 3
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int a[N];
int c[N];
int n;
void merge_work(int a[], int low, int mid, int high, int c[])
{
int l = low, r = mid + 1, k = 0;
while (l <= mid && r <= high)
{
if (a[l] >= a[r]) c[k ++] = a[r ++];
else c[k ++] = a[l ++];
}
while (l <= mid) c[k ++] = a[l ++];
while (r <= high) c[k ++] = a[r ++];
for (int m = 0; m < k; m ++) a[low + m] = c[m];
return;
}
void merge(int a[], int low, int high)
{
if (low < high)
{
int mid = (low + high) / 2;
merge(a, low, mid); merge(a, mid + 1, high);
merge_work(a, low, mid, high, c);
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i ++)
{
cin >> a[i];
}
merge(a, 1, n);
for (int i = 1; i <= n; i ++) cout << a[i] << " ";
return 0;
}