基础算法 – 归并排序
算法步骤
1,确定中间的分界点,
int mid = l + r >> 1;
2,进行递归分割,直到,最后只有一个数,或者没有数
merge_sort(l, mid);
merge_sort(mid + 1, r);
3, 对于已经划分成功的两部分,进行合并,需要用到额外int tmp[N];
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];
一、算法模板
#include<iostream>
using namespace std;
const int N = 100010;
int a[N];
int tmp[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;
int i = l, j = mid + 1;
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()
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
merge_sort(a, 0, n-1);
for(int i = 0; i < n; i++) printf("%d ", a[i]);
return 0;
}