利用递归的思想实现归并排序
#include <iostream>
using namespace std;
int a[1000], t[1000];
int n;
void merge_sort(int x, int y)
{
if(y - x > 1) //若左右端点相差不大于1,不能再分
{
int m = (x + y) >> 1;
int p = x, q = m, i = x;
merge_sort(x, m); //递归求解
merge_sort(m, y); //递归求解
while(p < m || q < y) //合并
{
if(q >= y || (p < m && a[p] <=a [q]))
t[i++] = a[p++]; //从左半数组复制到临时空间
else
t[i++] = a[q++]; //从右半数组复制到临时空间
}
for(i = x; i < y; i++)
a[i] = t[i];
}
}
int main()
{
int i;
while(cin >> n)
{
for(i = 1; i <= n; i++)
cin >> a[i];
merge_sort(1, n+1); //将元素a[1]~a[n]排序
for(i = 1; i <= n; i++)
cout << a[i] << ' ';
cout << endl;
}
return 0;
}