3

I have been learning insertion sort currently, and came up with this code:

public int[] Sort(int a[]){
    for(int i=1;i<a.length;i++){
        int term=a[i];
        int j=i-1;

        //Sorting
        while(j>=0 && term<a[j]){
            a[j+1]=a[j];
            j--;
        }

        a[j]=term;
    }

    return a;
}

But when i execute this code, it shows ArrayIndexOutofBoundsException. Please guide me wherever i am wrong.

1
  • I think the best lesson you can get here is learn to use the debugger. You can set the debugger to stop when there's an exception and then watch the values of the different variables. This usually helps to find what went wrong or at least can give a new direction of what to look for with the debugger. Commented Feb 15, 2014 at 6:09

2 Answers 2

2

According to the error status, it shows the error is on the

a[j] = term

So if you look at this closely you can see that while loop causes the ArrayIndexOutofBoundsException. So you can write the code like this:

public static int[] Sort(int a[]){
        for(int i=1;i<a.length;i++){
            int term=a[i];
            int j=i-1;

            //Sorting
            while(j>=0 && term<a[j]){
                a[j+1]=a[j];
                j--;
            }

            a[j+1]=term;
        }

        return a;
    }
Sign up to request clarification or add additional context in comments.

Comments

2

Reading the stack trace indicates that the error occurs on line

    a[j]=term;

Looking up, you can see that the while loop ends when j<0; therefore, you must be getting this error because j=-1. Experimentation reveals that your code works if you add j++; between the while and a[j]=term;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.