Hello im trying to code QuickSort, however I always meet an index out of bounds? My code is as followed:
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);
}
}
I'm using the code in the book: "Introduction to algorithms"
I'm trying to quick sort ArrayList
A
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("");
}
}
The problem is Collections.swap(A, A.get(i), A.get(j));
- this is going to try use the value in A.get(i)
as an index in your list, and obviously throws an out of bounds exception if the value at i
is greater than A.size()
.
So replace them with just the positions you want to swap:
Collections.swap(A, i, j);
and
Collections.swap(A, (i + 1), r);