算法思想;分而治之
算法步骤;
1. 确定分界点 x= ( l + r) /2
2. x 左边和右边分别归并排序
3. 将x左右两边的值合并
算法模版
#include<iostream>
using namespace std;
const int N = 100010;
int tmp[N];
int a[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 k = 0, i = l, j = mid + 1;
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(int i = l, j = 0; i <= r; i++) a[i] = tmp[j++];
}
说明:
归并时候申请了O(N) 的额外空间,为了防止元素的移动.