归并排序算法,参考网上http://blog.sina.com.cn/s/blog_4d3a41f401010jbf.html算法,测试并进一步修改。
void MergeArray(int a[], int first, int mid, int last)
{
int leftNum = mid-first+1, rightNum = last-mid;
int* left = (int*)malloc( leftNum * sizeof(int));
int* right = (int*)malloc( rightNum * sizeof(int));
//数据暂存
for (int i = 0; i < leftNum; ++i)left[i] = a[i+first];
for (int j = 0; j < rightNum; ++j)right[j] = a[mid+1+j];
int i = 0, j = 0, k = first;
//数据排序,并回写
while (i < leftNum && j < rightNum)
{
if (left[i] <= right[j])a[k++] = left[i++];
else a[k++] = right[j++];
}
//未比较完的数据回写
while(i < leftNum) a[k++] = left[i++];
while(j < rightNum) a[k++] = right[j++];
delete []left;
delete []right;
}
void Merge(int a[], int first, int last)
{
if (last > first)
{
int mid = (first+last)/2;
Merge(a, first, mid);
Merge(a, mid+1, last);
MergeArray(a, first, mid, last);
}
}