【问题标题】:Error in java code for merge sort用于合并排序的 java 代码中的错误
【发布时间】:2016-04-20 06:45:33
【问题描述】:

归并排序不是一种新算法,并且有可用的解决方案。我试图编写自己的代码,但它有一些逻辑错误。 关于我做错了什么的任何见解?

public class MergeSort {
    public static void main(String[] args) {

        int[] array = {5,4,8,3,7,10};
        mergeSort(array);
        System.out.println("Sorted array: \n");
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

    public static void mergeSort(int[] array) {
        if (array.length > 1) {
            int[] firstHalf = new int[array.length / 2];
            System.arraycopy(array, 0, firstHalf, 0, array.length / 2);
            mergeSort(firstHalf);

            int[] secondHalf = new int[array.length - array.length/2];
            System.arraycopy(array, array.length / 2, secondHalf, 0, array.length - array.length/2);
            mergeSort(secondHalf);

            merge(firstHalf, secondHalf, array);

        }
    }

    public static void merge(int[] firstHalf, int[] secondHalf, int[] array) {
        int i = 0;
        int j = 0;
        int k = 0;
        for (k = 0; k < array.length; k++) {
            for (i = 0, j = 0; i < firstHalf.length && j < secondHalf.length; i++, j++) {
                if (firstHalf[i] < secondHalf[j]) {
                    array[k] = firstHalf[i];
                    i++;

                } else if (secondHalf[j] < firstHalf[i]) {
                    array[k] = secondHalf[j];
                    j++;

                }
            }
        }

    }
}

【问题讨论】:

  • but it has some logical errors. 请详细说明。它做错了什么?给出一个失败的示例输入,以及失败的输出。如果您有运行时错误 - 提供完整的堆栈跟踪。如果它没有编译,告诉我们在哪里。
  • 没有上述细节。这个问题是题外话:Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers

标签: java algorithm sorting merge


【解决方案1】:

您的 merge() 函数存在多个问题:

  • 最明显的一个,merge() 不需要嵌套循环。笔记 你反复用 new 覆盖 array[k] 的值 价值观。
  • 另一个问题是在内循环的每次迭代中增加一个 ij 两次。
  • 此外,还有一些你永远不会接触的元素,其中一个数组中最大的元素(考虑如果你有一个已经排序的数组,所以你有left=[1,2,3] right=[4,5,6]。你弄清楚你只需要增加一个迭代器,而不是两者,您仍然会遇到一个问题,即您永远不会从left 触摸元素2,3)。

我的提示:在第一次实现算法时,尽量遵循一步一步的伪代码。如果您觉得自己明白了,请将其抹掉,然后在没有参考的情况下再次尝试书写。

【讨论】:

  • 谢谢!你的建议太贴切了。继续做好工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 2014-03-13
  • 2015-09-10
  • 2016-02-05
  • 1970-01-01
相关资源
最近更新 更多