简体   繁体   English

这个“ mergeSort”有什么问题?

[英]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 . infsup从未修改,因此inf始终小于sup The loop never terminates. 循环永远不会终止。

The problems in your merge sort (based in the comments): 合并排序中的问题(基于注释):

  1. 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并且永远不要更改infsup的值。 Change this for an if instead. 将其更改为if

      if (inf < sup) { //code goes here... } 
  2. 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 : 您只能在infsup之间移动元素:

     //for (i = 0; i <= sup; i++) { for (i = inf; i <= sup; i++) { //code goes here... } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM