用C语言根据void MergeSort(int* a, int begin, int end, int* temp)写出归并排序函数
时间: 2024-01-01 13:04:18 浏览: 63
void MergeSort(int* a, int begin, int end, int* temp) {
if (begin >= end) return;
int mid = (begin + end) / 2;
MergeSort(a, begin, mid, temp);
MergeSort(a, mid + 1, end, temp);
int i = begin, j = mid + 1, k = 0;
while (i <= mid && j <= end) {
if (a[i] <= a[j]) {
temp[k++] = a[i++];
} else {
temp[k++] = a[j++];
}
}
while (i <= mid) temp[k++] = a[i++];
while (j <= end) temp[k++] = a[j++];
for (i = 0; i < k; i++) {
a[begin + i] = temp[i];
}
}
相关问题
void mergeSort(int* nums, int begin, int end) { if (begin >= end) { return; } int len = end - begin+1; int mid = begin + (end - begin) / 2; mergeSort(nums, begin, mid); mergeSort(nums, mid+1, end); int* temp = new int[len]; temp = { 0 }; int l1 = begin, r1 = mid; int l2 = mid+1, r2 = end; int i = begin; for (; l1 <= r1 && l2 <= r2;) { if (nums[l1] < nums[l2]) { temp[i++] = nums[l1++]; } else { temp[i++] = nums[l2++]; } } for (; l1 <= r1;) { temp[i++] = nums[l1++]; } for (; l2 <= r2;) { temp[i++] = nums[l2++]; } for (int j = 0; j < len; j++) { nums[j+begin] = temp[j]; } } 出现读取访问冲突,修改代码
在代码中,`temp`被赋值为一个新的`int`数组,然后又被赋值为`{0}`,这样会导致`temp`指向了一个新的内存地址,原有的内存地址被泄漏。在后续的代码中,程序又对这个新的内存地址进行了读写操作,从而导致了读取访问冲突。为了解决这个问题,应该在申请`int`数组的同时,将数组中的元素全部初始化为0。修改后的代码如下:
```
void mergeSort(int* nums, int begin, int end) {
if (begin >= end) {
return;
}
int len = end - begin+1;
int mid = begin + (end - begin) / 2;
mergeSort(nums, begin, mid);
mergeSort(nums, mid+1, end);
int* temp = new int[len](); // 将数组中的元素全部初始化为0
int l1 = begin, r1 = mid;
int l2 = mid+1, r2 = end;
int i = begin;
for (; l1 <= r1 && l2 <= r2;) {
if (nums[l1] < nums[l2]) {
temp[i++] = nums[l1++];
}
else {
temp[i++] = nums[l2++];
}
}
for (; l1 <= r1;) { temp[i++] = nums[l1++]; }
for (; l2 <= r2;) { temp[i++] = nums[l2++]; }
for (int j = 0; j < len; j++) {
nums[j+begin] = temp[j];
}
delete[] temp; // 释放动态申请的内存空间
}
```
以下代码采用分而治之算法实现归并排序。请补充函数mergesort()的代码。提示:mergesort()函数可用递归实现,其中参数n在递归调用中不需要变化。 函数接口定义: void mergesort(int a[],int n,int left,int right);
```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);
}
}
```
阅读全文