归并排序

代码

#include <iostream>
using namespace std;

const int N = 100010;
int a[N], temp[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 = l;
    while (i <= mid && j <= r) {
        if (a[i] < a[j])
            temp[k ++] = a[i ++];
        else
            temp[k ++] = a[j ++];
    }

    while (i <= mid) temp[k ++] = a[i ++];
    while (j <= r) temp[k ++] = a[j ++];
    for (int i = l; i <= r; ++ i) a[i] = temp[i];
}

int main () {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; ++ i) scanf("%d", &a[i]);
    merge_sort(1, n);
    for (int i = 1; i <= n; ++ i) printf("%d ", a[i]);
    return 0;
}
最后修改于: