合并阶段需要开辟一个同原数组大小一样的数组来“组装”
void Merge(int arr[], int tmp[], int start, int mid, int end)//合并的过程
{
int i = start;
int j = mid+1;
int ktmp = start;//被复制到另一个数组上的数组下表
while(i < mid+1 && j < end+1)
{
if(arr[i] <= arr[j])
tmp[ktmp++] = arr[i++];
else
tmp[ktmp++] = arr[j++];
}
while(i != mid+1)
tmp[ktmp++] = arr[i++];
while(j != end+1)
tmp[ktmp++] = arr[j++];
for(int i = 0; i <= end; i++)
arr[i] = tmp[i];//再把重新排好序的数组拷贝回到原来的数组中
}
void MergeS(int arr[], int tmp[], int start, int end)
{
int mid = (start + end) / 2;
if(start < end)//分解
{
MergeS(arr, tmp, start, mid);
MergeS(arr, tmp, mid+1, end);
Merge(arr, tmp, start, mid, end);
}
}
void MergeSort(int arr[], int len)
{
int *tmp = (int *)malloc(sizeof(int) * len);
MergeS(arr, tmp, 0, len-1);
free(tmp);
}