算法:
分治法,先不断的二分,直到有序,第一次有序就是数组里只有一个数字。
然后递归合并数组,需要有辅助空间暂存合并后的数组,再更新原数组。
分:
void MergeSort(int a[],int first,int last,int temp[]){
if(first<last){
int mid = (first + last)/2;
MergeSort(a,first,mid,temp);
MergeSort(a,mid+1,last,temp);
MergeArray(a,first,mid,last,temp);
}
}
合:
void MergeArray(int a[],int first,int mid,int last,int temp[]){
//第一个数组
int i = first;int m = mid;
//第二个数组
int j = mid+1;int n = last;
//结果数组
int k = 0;
while(i<=m &&j<=n){
if(a[i]<a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while(i<=m)
temp[k++] = a[i++];
while(j<= n)
temp[k++] = a[j++];
//更新排序后的原数组
for (int i = 0; i < k; i++)
{
a[i+first] = temp[i];
}
}