Thomas Catinella
Thomas Catinella

Reputation: 11

Quicksort - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1

Learning to code, I will be attending a boot camp in early 2019 and looking to prepare for it. I have a Java book with the following code for an example of the quicksort algorithm, I have copied it directly from the book and it provides me the IndexOutOfBounds error. I understand it has to do with an Index's location that is being checked but may not exist, however, I can't tell what is wrong specifically. Any help? Thanks in advance.

// Try This 6-3: A simple version of the Quicksort. 

class Quicksort {

    // Set up a call to the actual Quicksort method.
    static void qsort(char items[]) {
        qs(items, 0, items.length-1);
    }

    // A recursive version of Quicksort for characters. 
    private static void qs(char items[], int left, int right)
    {
        int i, j;
        char x, y;

        i = left; j = right;
        x = items[(left+right)/2];

        do {
            while((items[i] < x) && (i < right))
                i++;

            while((x < items[j]) && (j > left))
                j--;

            if(i <= j) {
                y = items[i];
                items[i] = items[j];
                items[j] = y;

                i++; 
                j--;
            }
        } while(i <= j);

        if(left < j);
            qs(items, left, j);

        if(i < right)
            qs(items, i, right);
    }
}

class QSDemo { 
    public static void main(String args[]) {
        char a[] = {'d', 'x', 'a', 'r', 'p', 'j', 'i'};
        int i; 

        System.out.println("Original array: ");

        for(i = 0; i < a.length; i++)
            System.out.print(a[i]);

        System.out.println();

        // now, sort the array
        Quicksort.qsort(a);

        System.out.print("Sorted array: ");

        for(i = 0; i < a.length; i++)
            System.out.print(a[i]);
    }
}*emphasized text*

Upvotes: 1

Views: 80

Answers (2)

Harshith Rai
Harshith Rai

Reputation: 3066

Check your second if loop in the qs() function, where it checks if left is less than j. You have added a semi-colon (may be accidentally) after the if statement. This causes the statement meant to be inside the if loop to be executed regardless of whether the if condition passes or not.

Here is what it should be:

if(left < j)             //remove semi-colon which was here
    qs(items, left, j);

Upvotes: 1

suvojit_007
suvojit_007

Reputation: 1728

The problem is you have put an ; after the if statement and that's the reason you're getting the error. Because of ; , qs() will be called regardless of the if condition.

    if(left < j); qs(items, left, j); //<------problem
    ____________^

if(left < j); qs(items, left, j); should be if(left < j) qs(items, left, j);

Upvotes: 1

Related Questions