Whenever I try to run this code on the array
int arr[]= {64,32,85,11,56,23};
it runs fine but when I try to run the same code on this array
int arr[] = {43,32,22,78,63,57,91,13};
it throws ArrayIndexOutOfBoundsException
. Why is this exception thrown?
public class QuickSort {
static void swap(int arr[], int index1, int index2){
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp ;
}
static int partition(int arr[], int start, int end){
int pivot = arr[start], i = start, j = end ;
while(i <= j){
while(arr[i] <= pivot) i++ ;
while(arr[j] > pivot) j-- ;
if(i <= j){
swap(arr,i,j); i++ ; j-- ;
}
}
swap(arr,start,j);
return j ;
}
static void quick_sort(int arr[], int start, int end){
if(start < end){
int j = partition(arr,start,end);
quick_sort(arr, start, j);
quick_sort(arr, j+1, end);
}
}
static void print(int arr[]){ for(int i = 0; i< arr.length ; i++ ) System.out.print(arr[i] + " ");}
public static void main(String ...s){
int arr[] = {43,32,22,78,63,57,91,13};
quick_sort(arr, 0, arr.length-1);
print(arr);
}
}
Exception Stack Trace :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8
at QuickSort.partition(Quick Sort.java:11)
at QuickSort.quick_sort(Quick Sort.java:22)
at QuickSort.quick_sort(Quick Sort.java:24)
at QuickSort.quick_sort(Quick Sort.java:24)
at QuickSort.main(Quick Sort.java:32)