【发布时间】: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