#include<iostream>
using namespace std;
void swap(int *a,int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
//分治法,将数组分成两组A,B若这两组内数据都是有序的,将两个有序数列合并
void merge_arr(int a[],int first,int mid,int last,int tmp[])
{
int i =first,j = mid + 1;
int m = mid, n = last;
int k = 0;
while(i<=m&&j<=n)
{
if(a[i]<a[j])
tmp[k++] = a[i++];
if(a[i]>a[j])
tmp[k++] = a[j++];
}
while(i<=m)
tmp[k++] = a[i++];
while(j<=n)
tmp[k++] = a[j++];
for(i = 0;i<k;i++)
a[first+i] = tmp[i];//这里first要加上,因为前面first个数据已经有序
}
void merge_sort(int a[],int first,int last,int tmp[])
{
if(first<last)
{
int mid = (first + last)/2;
merge_sort(a,first,mid,tmp);
merge_sort(a,mid+1,last,tmp);
merge_arr(a,first,mid,last,tmp);
}
}
void main()
{
int a[11] = {1,3,5,7,2,8,4,9,6,0,10};
int tmp[11] = {0};
merge_sort(a,0,10,tmp);
for(int i = 0;i<11;i++)
{
printf("%d \n",a[i]);
}
system("pause");
return;
}