基础算法_01_排序_02_归并排序
作者:
综上所述_
,
2024-09-05 12:48:01
,
所有人可见
,
阅读 2
merge_sort
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 100010;
int n, a[N], tmp[N];
void merge_sort(int a[], int l, int r) {
if (l >= r) return;
int mid = l + r >> 1;
merge_sort(a, l, mid), merge_sort(a, mid + 1, r);
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r) {
if (a[i] <= a[j]) tmp[k++] = a[i++];
else tmp[k++] = a[j++];
}
while (i <= mid) tmp[k++] = a[i++];
while (j <= r) tmp[k++] = a[j++];
for (i = l, j = 0; i <= r; i++, j++) a[i] = tmp[j]; // 如果i = 0,每次归并都会打乱排好的a
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
merge_sort(a, 0, n - 1);
for (int i = 0; i < n; i++) cout << a[i] << " ";
return 0;
}