【模板】归并排序

发布于 2022-07-25  4 次阅读


#include <bits/stdc++.h>

using namespace std;
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 998244353;
int n, a[N];

void my_sort(int q[], int l, int r) {
    if (l >= r) return;
    int mid = (l + r) >> 1;
    my_sort(q, l, mid), my_sort(q, mid + 1, r);
    int k = 0, i = l, j = mid + 1, tmp[r - l + 1];
    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 (k = 0, i = l; i <= r; k++, i++) q[i] = tmp[k];
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) scanf("%d", a + i);
    my_sort(a, 1, n);
    for (int i = 1; i <= n; ++i) printf("%d ", a[i]);
    return 0;
}