I am writing code for quicksort but get an arrayindexoutofbounds exception. I am new to java and need help figuring out what is causing it and how to fix it.
My main
Integer[] A ;
System.out.println(" LENGTH SELECTION MERGE QUICK JAVA") ;
for (int length = startLength ; true ; length += incrementLength) {
System.out.printf("%10d", length ) ;
A = makeRandomArray(length,maximumElement) ;
startTimer() ;
SortingMethods.selectionSort(A) ;
System.out.printf("%12d", getElapsedTime() ) ;
A = makeRandomArray(length,maximumElement) ;
startTimer() ;
SortingMethods.mergeSort(A, A[0], A[A.length-1]) ;
System.out.printf("%12d", getElapsedTime() ) ;
A = makeRandomArray(length,maximumElement) ;
startTimer() ;
SortingMethods.quickSort(A, A[0], A[A.length-1]) ;
System.out.printf("%12d", getElapsedTime() ) ;
A = makeRandomArray(length,maximumElement) ;
startTimer() ;
Arrays.sort(A) ;
System.out.printf("%12d", getElapsedTime() ) ;
System.out.println() ;
System.out.println() ;
}
}
And my quicksort is as follows:
public static <T extends Comparable<T>> void quickSort(T[] A, int left, int right) // quick sort
{
if (right <= left) return;
int i = partition(A, left, right);
quickSort(A, left, i-1);
quickSort(A, i+1, right);
}
private static <T extends Comparable<T>> int partition(T[] a, int left, int right) {
int i = left - 1;
int j = right;
while (true) {
while (less(a, a[++i], a[right])); // find item on left to swap
// a[right] acts as sentinel
while (less(a, a[right], a[--j])) // find item on right to swap
if (j == left) break; // don't go out-of-bounds
if (i >= j) break; // check if pointers cross
exch(a, i, j); // swap two elements into place
}
exch(a, i, right); // swap with partition element
return i;
}
// is x < y ?
private static <T extends Comparable<T>> boolean less(T[] a, T x, T y) {
return (true);
}
// exchange a[i] and a[j]
private static <T extends Comparable<T>> void exch(T[] a, int i, int j) {
T swap = a[i];
a[i] = a[j];
a[j] = swap;
}
Thanks

New Topic/Question
Reply




MultiQuote







|