[英]What's wrong in this “mergeSort”?
There's a mergeSort code that I copied at class lesson, can you help me to find the errors? 我在上课时复制了一个mergeSort代码,您能帮我发现错误吗?
When I run the main that use mergeSort
the program enters in an infinite loop but doesn't display any error. 当我运行使用
mergeSort
的主程序时,程序会进入无限循环,但不会显示任何错误。 I tried to run in debug mode but I am not very expert and I don't find what's wrong. 我试图在调试模式下运行,但是我不是很熟练,也没有发现什么问题。 However I think that the error is in
mergeSort(int[] v, int inf, int sup)
recursion. 但是我认为错误是在
mergeSort(int[] v, int inf, int sup)
递归中。
public class CopyOfSortMethods {
private static void merge(int[] v, int inf, int med, int sup) {
int aux[] = new int[v.length];
int i = inf;
int j = med + 1;
int k = inf;
while ((i <= med) && (j <= sup)) {
if (v[i] < v[j]) {
aux[k] = v[i];
i++;
k++;
} else {
aux[k] = v[j];
j++;
k++;
}
}
while (i <= med) {
aux[k] = v[i];
i++;
k++;
}
while (j <= sup) {
aux[k] = v[j];
j++;
k++;
}
for (i = 0; i <= sup; i++) {
v[i] = aux[i];
}
}
public static void mergeSort(int[] v, int inf, int sup) {
int med;
while (inf < sup){
med = (inf + sup)/2;
mergeSort(v, inf, med);
mergeSort(v, med + 1, sup);
merge(v, inf, med, sup);
}
}
public static void mergeSort(int[] v) {
if(v!=null) {
mergeSort(v, 0, v.length - 1);
}
}
}
As Maverik points out, the issue is the while
loop in mergeSort()
. 正如Maverik所指出的那样,问题在于
mergeSort()
的while
循环。
inf
and sup
are never modified, so inf
is always less than sup
. inf
和sup
从未修改,因此inf
始终小于sup
。 The loop never terminates. 循环永远不会终止。
The problems in your merge sort (based in the comments): 合并排序中的问题(基于注释):
In mergeSort
method, you're recursively calling the mergeSort
inside a while
loop and never changing the values of inf
and sup
. 在
mergeSort
方法中,您将在while
循环内递归调用mergeSort
while
并且永远不要更改inf
和sup
的值。 Change this for an if
instead. 将其更改为
if
。
if (inf < sup) { //code goes here... }
In your merge
sort, at the bottom of the method body, you're moving the items all the items from aux
array to v
array. 在
merge
排序中,在方法主体的底部,将所有项目从aux
数组移到v
数组。 You should only move the elements between inf
and sup
: 您只能在
inf
和sup
之间移动元素:
//for (i = 0; i <= sup; i++) { for (i = inf; i <= sup; i++) { //code goes here... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.