【发布时间】:2021-07-11 22:21:13
【问题描述】:
我正在实施合并排序,将极客引用作为极客实施的指南,但我的实施不起作用。
我有我的合并排序函数,它将给定的数组分成 2 部分,并在列表的一半上调用合并排序。
在合并排序中,我使用一个辅助函数将子数组合并在一起。
我已经包含了我的 2 个函数。谁能成为我的第二双眼睛,我盯着这个太久了,无法分辨 1 和 l 之间的区别
它正在运行,但排序不正确。
void merge(int arr[], int temp[], int l, int m, int r) {
//TODO: implement merge.
// check arr
if (arr == NULL) {
return;
}
int left = m - l + 1;
int right = r - m;
// copy array into temp array
// first half
int i = 0;
for (i = 0; i < left; i++) {
temp[i] = arr[l + i];
}
// second half
int j = 0;
for (j = m + 1; i < right; j++) {
temp[j] = arr[m + l + i];
}
// compare from each end inserting the lower into the next location of the real array
// beginning index of front sub list
int front = 0;
// beginning of back sub list
int back = left;
// index within array to insert back in
int index = l;
while ((front < left) && (back < right)) {
if (temp[front] <= temp[back]) {
// temp front goes in the next array spot
arr[index] = temp[front];
// increase temp
front++;
} else {
// back is smaller and is put back in the list first
arr[index] = temp[back];
// increase back
back++;
}
// increase array index
index++;
}
while (front < left) {
arr[index] = temp[front];
front++;
index++;
}
while (back < right) {
arr[index] = temp[back];
back++;
index++;
}
}
void mergeSort(int array[], int temp[], int l, int r) {
if (r > l) {
// find middle point
int middle = l + (r - l) / 2;
// call merge on first half
mergeSort(array, temp, l, middle);
// call merge on second half
mergeSort(array, temp, middle + 1, r);
// merge the halves
merge(array, temp, l, middle, r);
}
}
【问题讨论】:
-
至少,在你的 last
while循环中,我想你想要:arr[back] = temp[back];-->arr[index] = temp[back]; -
您是否在调试器中运行程序并在运行时对其进行跟踪?如果有,你发现了什么?它首先从哪里开始出错?
-
这个循环
for(i = 0; i < r + 1; i++) {完全覆盖了前一个循环的结果,如果m不是零,它复制了太多的数组(并且索引越界)。 -
@TomKarzes - 感谢您指出这一行,我意识到我没有更新最新的代码。它已经过编辑以反映我最近的提交
-
此时听起来您正在使用的代码与发布的代码完全不同。如果是这样,那么您应该更新您的代码,或者删除问题。