归并思想是将问题分解为更小的、同性质的子问题,求解子问题,然后合并子问题的解得到原问题的解。经历一个分界、求解、合并的过程。因此上归并排序为将数组分为若干个子数组,分别排序,然后合并子数组的排序结果,即合并两个排序的数组,相关代码如下:
void MergeAubArray(int res[], int a[], int left, int mid, int right) //子数组以mid为界,下边为left~mid,mid+1 ~ right , res[] 为结果暂时存放的数组
{
int left_a = left;
int left_b = mid + 1;
int k = left;
while (left_a <= mid && left_b <= right) { //子数组未合并完
if (a[left_a] < a[left_b]) {
res[k++] = a[left_a++];
}
else {
res[k++] = a[left_b++];
}
}
while (left_a <= mid) { //a子数组未合并完,复制剩余元素
res[k++] = a[left_a++];
}
while (left_b <= right) { //b数组未合并完,赋值剩余元素
res[k++] = a[left_b++];
}
for (int i = left; i <= right; i++) { //将合并结果赋值到原数组
a[i] = res[i];
}
return;
}
归并排序算法:
void EX_SortMerge(int res[], int a[], int left, int right)
{
if (left >= right) {
return;
}
int mid = (right - left) / 2 + left;
EX_SortMerge(res, a, left, mid);
EX_SortMerge(res, a, mid + 1, right);
MergeAubArray(res, a, left, mid, right);
return;
}