【发布时间】:2019-03-09 21:07:48
【问题描述】:
您好,我正在尝试编写 QuickSort 代码,但是我总是遇到超出范围的索引? 我的代码如下:
public class QuickSort
{
public void quickSort(ArrayList<Integer> A, int p, int r)
{
if (p < r) {
int q = partition(A, p, r);
quickSort(A, p, q - 1);
quickSort(A, q + 1, r);
}
}
public int partition(ArrayList<Integer> A, int p, int r) {
int x = A.get(r);
int i = p - 1;
for (int j = p ; j < r; j++) {
if (A.get(j) <= x) {
i++;
Collections.swap(A, A.get(i), A.get(j));
}
}
Collections.swap(A, A.get(i + 1), A.get(r));
return (i + 1);
}
}
我用的是书中的代码:《算法导论》
我正在尝试快速排序ArrayListA
public class TestDriver
{
public static void testQuick() {
//Laver et random array A
ArrayList<Integer> A = new ArrayList<>();
for (int i = 1; i <12; i++) {
A.add(i);
}
Collections.shuffle(A);
int n = A.size();
QuickSort qs = new QuickSort();
System.out.println("The Array");
System.out.println(A);
qs.quickSort(A, 0, (n - 1));
System.out.println("The Array after QuickSort");
System.out.println(A);
System.out.println("");
}
}
【问题讨论】:
-
猜测,
for循环应该是for (int j = p ; j < r - 1; j++) { -
也给出了超出范围的索引:(
-
您能告诉我们
A,以及p和r传递的值吗? -
当然,已将其添加到问题中。我将 p 作为开始( 0 ),将 r 作为结束 A.size - 1
标签: java arraylist indexoutofboundsexception quicksort