java.lang.ArrayIndexOutOfBoundsJava 中的线程"main"异常错误



我现在正在用java编写一个快速排序程序,但遇到了一个错误。终端显示

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 101 out of bounds for length 19
at QuickSort.swap(qs.java:16)
at QuickSort.partition(qs.java:23)
at QuickSort.quickSort(qs.java:9)
at QuickSort.quickSort(qs.java:5)
at QuickSort.main(qs.java:40)

这是我第一次用java编程,当我在下面的程序中用一个10大小的数组和另一个与数组大小相同的数组进行测试时,没有出现这个错误。

我做了研究,当程序访问错误的索引数组或超出循环范围时,就会出现这个错误,但它可以与其他大小相同的数组一起使用。

import java.util.Arrays;
public class QuickSort {
public void quickSort(int[] A) {
quickSort(A, 0, A.length - 1);
}
private void quickSort(int[] A, int low, int high) {
if (low < high + 1) {
int p = partition(A, low, high);
quickSort(A, low, p - 1);
quickSort(A, p + 1, high);
}
}
private void swap(int[] A, int index1, int index2) {
int temp = A[index1];
A[index1] = A[index2];
A[index2] = temp;
}
private int getPivot(int[] A, int low, int high) {
return A[low];
}
private int partition(int[] A, int low, int high) {
swap(A, low, getPivot(A, low, high));
int border = low + 1;
for (int i = border; i <= high; i++) {
if (A[i] < A[low]) {
swap(A, i, border++);
}
}
swap(A, low, border - 1);
return border - 1;
}
public static void main(String[] args) {
QuickSort qs = new QuickSort();
int[] A = {101,103,102,107,110,116,114,118,112,111,109,104,117,100,105,115,113,106,119};
System.out.println(Arrays.toString(A));
long start = System.nanoTime();
qs.quickSort(A);
long end = System.nanoTime();
long elapsed_secs = end - start;
double seoconds = (double)elapsed_secs / 1_000_000_000.0;
System.out.println(Arrays.toString(A));
System.out.println(seoconds);
}
}

检查此

private int getPivot(int[] A, int low, int high) {
return A[low];
}

int[] A = {101,103,102,107,110,116,114,118,112,111,109,104,117,100,105,115,113,106,119};

第一次,101->在索引101处获得值A,但A的大小是19->异常

您想用getPivot做什么?

仅凭评论

swap(A, low, getPivot(A, low, high));

结果:

[101, 103, 102, 107, 110, 116, 114, 118, 112, 111, 109, 104, 117, 100, 105, 115, 113, 106, 119]
[100, 101, 102, 103, 104, 105, 106, 107, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119]

相关内容

最新更新