I'm now writing a quicksort program in java and encountered an error. The terminal says that
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)
this is my first programming in java and this error did not occur when I tested this with an array that is a size of 10 and another array that has the same size to the array in the following program.
I did my research and this error occurs when the program access the wrong indexed array or out of range of loops but it works with other arrays that have the same size.
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);
}
}