Question

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.

Was it helpful?

Solution

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;
    }

OTHER TIPS

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;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top