我正在尝试使用eclipse IDE在Java中实现MergeSort算法。 我收到了以下错误
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
它包含三种方法:merge()
,mergeSort()
和printArray()
public class MergeSort {
public static void main(String[] args) {
int[] numbers = { 10, 5, 3, 7, 6, 2, 21, 4 };
mergeSort(numbers);
printArray(numbers);
}
public static int[] mergeSort(int[] A) {
int n = A.length;
if (n < 2) {
return A;
}
int mid = n / 2;
int[] left = new int[mid];
int[] right = new int[n - mid];
for (int i = 0; i < mid - 1; i++) {
left[i] = A[i];
}
for (int i = mid; i < n - 1; i++) {
right[i - mid] = A[i];
}
mergeSort(left);
mergeSort(right);
merge(left, right);
return A;
}
public static int[] merge(int[] A, int[] B) {
int[] C = new int[A.length + B.length];
int i = 0;
int j = 0;
int k = 0;
int nL = A.length;
int nR = B.length;
while (i < nL && j < nR) {
if (A[i] <= B[j]) {
C[k] = A[i];
k = k + 1;
i = i + 1;
} else {
C[k] = A[j];
j = j + 1;
}
k = k + 1;
}
while (i < nL) {
C[k] = A[i];
i = i + 1;
k = k + 1;
}
while (j < nR) {
C[k] = B[j];
j = j + 1;
k = k + 1;
}
return C;
}
public static void printArray(int[] A) {
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
}
}
答案 0 :(得分:3)
while
方法中的第一个merge()
循环有问题。您已将A[j]
分配给C[k]
,而它应为B[j]
。此外,您为k
条件增加if
两次。
将while循环更改为:
while (i < nL && j < nR) {
if (A[i] <= B[j]) {
C[k] = A[i];
i = i + 1;
} else {
C[k] = B[j];
j = j + 1;
}
k = k + 1;
}
但是,除此问题外,您的代码还存在其他问题。
首先,您的循环范围不正确。目前,您错过了(mid - 1)
th 和(n - 1)
th 元素。将你的循环改为:
for (int i = 0; i < mid; i++) {
left[i] = A[i];
}
for (int i = mid; i < n; i++) {
right[i - mid] = A[i];
}
其次,您的mergeSort()
方法会创建一个新数组。您当前没有使用返回值。将返回值分别重新分配给left
和right
:
left = mergeSort(left);
right = mergeSort(right);
return merge(left, right);
最后,最终结果还需要重新分配给numbers
数组:
numbers = mergeSort(numbers);
printArray(numbers);