0

Here is a method to perform insertion sorting in Java that I encountered while learning AP Computer Science:

public static void insertionSort(int[] x)
{
    for (int i=1;i<x.length;i++)
    {
        int temp = x[i];
        int j=i-1;
        while (temp<x[j]&&j>=0)
        {
            x[j+1]=x[j];
            j--;
        }
        x[j+1]=temp;
    }
}

Logically, I think the code is correct. However, when I try to sort a list using the method by using the following code:

public static void main(String[] args)
{
    int[] numList ={9,3,12,765,23};
    insertionSort(numList);
    for (int num:numList)
    {
     System.out.println(num);
    }
}

I get the following exception: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5

What is the problem here?

  • 1
    Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Sudhir Ojha Mar 02 '21 at 04:51
  • modify your condition for while as below, that should solve the problem : while (j>=0 && temp – akshaya pandey Mar 02 '21 at 04:53
  • Look at the entire stacktrace You'll see something like in it `Test.insertionSort(Test.java:42)` it tells that line 42 is causing the exception. – onkar ruikar Mar 02 '21 at 04:55

3 Answers3

0

use while (j>=0&&temp<x[j]) not while (temp<x[j]&&j>=0)

onkar ruikar
  • 1,641
  • 1
  • 4
  • 14
0

You've hit an evaluation order issue. Your condition (temp < x[j] and j >= 0) is correct, but due to the order you've written them, x[j] is evaluated to compare with temp before it's compared with 0. Reverse your conditions to j >= 0 && temp < x[j] to resolve.

Thanks to short circuit evaluation (https://en.wikipedia.org/wiki/Short-circuit_evaluation), x[j] will not be evaluated due to j >= 0 being false.

0

In while loop in insertionSort method your statement should be like this

while (j >= 0 && x[j] > temp)