归并排序本质上也是一种分治算法(非常经典)。 稳定排序:相同元素的相对次序在排序后不会发生变化 其基本流程如下: 确定分界点:一般是中间点(l + r) / 2。递归排序左右区间。归并:将两个有序数组合并为一个有序数组。(双指针算法,需要借助额外空间,类似于数据库中根据两个Page的值将结果输出到另一个Page中去) 其代码如下: 123456789101112131415161718192021222324252627282930313233343536373839404142434445#include <iostream>using namespace std;const int N = 1e5 + 10;int a[N], tmp[N];void merge_sort(int *nums, int l, int r) { if (l >= r) return; int mid = (l + r) / 2; merge_sort(nums, l, mid); merge_sort(nums, mid + 1, r); int k = 0, i = l, j = mid + 1; while (i <= mid && j <= r) { if (nums[i] <= nums[j]) { tmp[k++] = nums[i++]; } else { tmp[k++] = nums[j++]; } } while (i <= mid) tmp[k++] = nums[i++]; while (j <= r) tmp[k++] = nums[j++]; for (i = l, k = 0; i <= r; i++, k++) { nums[i] = tmp[k]; }}int main() { int N; cin >> N; int nums[N]; for (int i = 0; i < N; i++) { cin >> nums[i]; } merge_sort(nums, 0, N - 1); for (int i = 0; i < N; i++) { cout << nums[i] << " "; } cout << endl;}