以下代码采用分而治之算法实现归并排序。请补充函数mergesort()的代码。提示:mergesort()函数可用递归实现,其中参数n在递归调用中不需要变化。 函数接口定义: void mergesort(int a[],int n,int left,int right);
时间: 2024-05-13 08:19:43 浏览: 71
MergeSort:归并排序算法的实现
```c++
void merge(int a[], int left, int mid, int right) {
int i = left;
int j = mid + 1;
int k = 0;
int* tmp = new int[right - left + 1];
while (i <= mid && j <= right) {
if (a[i] <= a[j]) {
tmp[k++] = a[i++];
}
else {
tmp[k++] = a[j++];
}
}
while (i <= mid) {
tmp[k++] = a[i++];
}
while (j <= right) {
tmp[k++] = a[j++];
}
for (int x = 0; x < k; x++) {
a[left + x] = tmp[x];
}
delete[] tmp;
}
void mergesort(int a[], int n, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergesort(a, n, left, mid);
mergesort(a, n, mid + 1, right);
merge(a, left, mid, right);
}
}
```
阅读全文