Error in insertion sort technique

I am studying insertion sorting now 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 go wrong.

+3
source share
2 answers

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

a[j] = term

So, if you look closely at this, you will see that while loop throws an ArrayIndexOutofBoundsException. Thus, you can write the code as follows:

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;
    }
+2
source

Reading a stack trace indicates that an error occurs on a line

    a[j]=term;

, , while , j < 0; , j = -1. , , j++; while a[j]=term;

+2

All Articles