归并排序
排序过程
1. 将数组划分成两个部分,分别进行递归排序
2. 将排序后的两部分,利用双指针的思想,进行归并
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int a[N];
int s[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 k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r) {
if (q[i] <= q[j]) s[k++] = q[i++];
else s[k++] = q[j++];
}
while (i <= mid) s[k++] = q[i++];
while (j <= r) s[k++] = q[j++];
for (int i = l, j = 0; i <= r; i++, j++) q[i] = s[j];
}
int main() {
int n;
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;
}