归并排序

  • **时间复杂度:O(nlogn)**。

  • 步骤:

    1. 确定分界点mid=(l+r)。
    2. 归并排序左右两段。
    3. 有序归并,合二为一。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
int q[maxn], tmp[maxn], n;

void ms(int q[], int l, int r) {
if (l >= r) return;
int mid = l + r >> 1;
ms(q, l, mid), ms(q, mid + 1, r);

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

int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &q[i]);

ms(q, 0, n - 1);

for (int i = 0; i < n; i++) printf("%d ", q[i]);
return 0;
}