Java 快速排序索引自动查找异常arraylist
您好,我正在尝试编写快速排序代码,但是我总是遇到索引超出范围? 我的代码如下:Java 快速排序索引自动查找异常arraylist,java,arraylist,indexoutofboundsexception,quicksort,Java,Arraylist,Indexoutofboundsexception,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);
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);
}
}
问题是
Collections.swap(A,A.get(i),A.get(j))
-这将尝试使用A.get(i)
中的值作为列表中的索引,如果i
处的值大于A.size()
,显然会抛出越界异常
因此,将它们替换为您想要交换的位置:
Collections.swap(A, i, j);
及
猜测一下,
for
循环应该是for(intj=p;j
也给出了一个超出范围的索引:(你能给我们看一下a
,哪些值被作为p
和r
传递吗?当然,已经把它添加到问题中了。我把p作为开始(0)传递,把r作为结束a.size-1传递
Collections.swap(A, i, j);
Collections.swap(A, (i + 1), r);