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?