0

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)
  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Bashir Apr 09 '20 at 11:07
  • I know, this might feel frustrating, but please understand: this is a very common problem. **Some** part of your code makes assumptions about the size of your array that simple dont match your array. The exception gives you all the details you need to look at. In other words: this is part of learning. You have to isolate the error, and that exception gives you the clues where to start. – GhostCat Apr 09 '20 at 11:11
  • Also: please include the exception stack trace in your question. It is great that you have a complete example, but dont expect people to download and run things for themselves. – GhostCat Apr 09 '20 at 11:11
  • Thanks for catching that. I've added Exception Stack Trace. – anonymous_entity Apr 09 '20 at 11:24
  • You have a bug in your algorithm, because, at some point during the execution of your code, the value of `i` is 8 but the largest index for array `arr` is 7, on this line of the code you posted in your question: `while(arr[i] <= pivot) i++ ;` – Abra Apr 09 '20 at 11:27

0 Answers0