// 归并排序法
void Merge(int arr[], int left, int mid, int right)
{
int i = left;
int j = mid + 1;
int *temp = new int[ right - left + 2] ; //注意生成数组空间的大小,要大于原数组长度,否则溢出
for (int k = left; k <= right; k++)
{
if (i > mid)
{
temp[k] = arr[j++];
}
else if (j > right)
{
temp[k] = arr[i++];
}
else if (arr[i] <= arr[j])
{
temp[k] = arr[i++];
}
else
{
temp[k] = arr[j++];
}
}
for (int k = left; k <= right; k++)
{
arr[k] = temp[k];
}
}
void MergeSort(int arr[],int left,int right)
{
if (left < right)
{
int mid = (left + right) / 2;
MergeSort(arr, left, mid);
MergeSort(arr, mid + 1, right);
Merge(arr, left, mid, right);
}
}
C++ 归并排序
最新推荐文章于 2024-06-01 20:09:00 发布