如何解决mergesort算法合并功能不起作用
我正在尝试制作自己的版本的mergesort,但是,我对如何按顺序将两个数组合并回单个数组感到困惑。
下面是我的代码,在我尝试运行该程序后,弹出了一些对我来说没有意义的数字,例如776247896 327641 57752310
。
谁能告诉我我的代码出了什么问题?请赐教。非常感谢。
//nL is the length of left[]
//nR is the length of right[]
//nA is the length of A[]
void merge(int left[],int nL,int right[],int nR,int A[],int nA) {
int temp[nA];
int i = 0,j = 0,k = 0;
while (i < nL && j < nR) {
if (left[i] <= right[j]) {
temp[k++] = left[i++];
}
else if (left[i] > right[j]) {
temp[k++] = right[j++];
}
}
while (i == nL && j < nR && k < nA) {
temp[k++] = right[j++];
}
while (j == nR && i < nL && k < nA) {
temp[k++] = left[i++];
}
for (int m = 0; m < nA; m++) {
temp[m] = A[m];
}
}
int main(void) {
int left[4] = { 13,22,25,60};
int right[4] = { 9,11,27,55};
int sorted[8];
merge(left,4,right,sorted,8);
for (int i = 0; i < 8; i++) {
printf("%i\n",sorted[i]);
}
}
解决方法
是否应该撤消?
temp[m] = A[m];
因此,数组A充满了存储在堆栈中的随机字节。
, merge
函数中的最后循环不会从temp
复制回到A
,而是相反。它应该更改为:
for (int m = 0; m < nA; m++) {
A[m] = temp[m];
}
还请注意以下说明:
-
目标数组的长度应为左右数组长度的总和,无需指定。
-
测试
else if (left[i] > right[j])
是多余的,应将其删除。 -
测试
while (i == nL && j < nR && k < nA)
也是多余的:在第一个循环结束时,i == nL
或j == nR
或两者兼有。您只需编写while (j < nR)
,下面的循环也可以简化。
这是修改后的版本:
#include <stdio.h>
//nL is the length of left[]
//nR is the length of right[]
//nA is the length of A[]
void merge(int left[],int nL,int right[],int nR,int A[]) {
int temp[nL + nR];
int i = 0,j = 0,k = 0;
while (i < nL && j < nR) {
if (left[i] <= right[j]) {
temp[k++] = left[i++];
} else {
temp[k++] = right[j++];
}
}
while (i < nL) {
temp[k++] = left[i++];
}
while (j < nR) {
temp[k++] = right[j++];
}
for (int m = 0; m < k; m++) {
A[m] = temp[m];
}
}
int main(void) {
int left[4] = { 13,22,25,60};
int right[4] = { 9,11,27,55};
int sorted[8];
merge(left,4,right,sorted);
for (int i = 0; i < 8; i++) {
printf("%i\n",sorted[i]);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。