-1

Why do I get ArrayIndexOutOfBoundsException: 1in my Insertion sort on this line: while ((a[j].compareTo(a[j - 1]) > 0) && j > 0)

 public static <T extends Comparable> void inserionSort(T[] a) {
            int j, i;
            for (i = 1; i < a.length; i++) {
                //initial condition 
                j = i;
                while ((a[j].compareTo(a[j - 1]) > 0) && j > 0) {
                     
                    swap(j, j - 1, a); 
                    j--;
                }
                 
            }
            display(a);
    
        }

Is there any problem with my algorithm?

Shahed A.
  • 17
  • 4

2 Answers2

1

You are checking j > 0 after (a[j].compareTo(a[j - 1]) , hence in case of j == 0 a[0-1] will be evaluated before j > 0.

notFound
  • 50
  • 8
1

Initially, j = 1 and after swapping j becomes 0. And a[j-1] is a[-1] which gives you that exception.

If you put j>0 before the condition, it should work

Marat
  • 1,288
  • 2
  • 11
  • 22