Hello,
I am in learning java. I try this code that I got from internet :
static void insertionSort(int[] A) {
// Sort the array A into increasing order.
int itemsSorted; // Number of items that have been sorted so far.
for (itemsSorted = 1; itemsSorted < A.length; itemsSorted++) {
// Assume that items A[0], A[1], ... A[itemsSorted-1]
// have already been sorted. Insert A[itemsSorted]
// into the sorted part of the list.
int temp = A[itemsSorted]; // The item to be inserted.
int loc = itemsSorted - 1; // Start at end of list.
while (loc >= 0 && A[loc] > temp) {
A[loc + 1] = A[loc]; // Bump item from A[loc] up to loc+1.
loc = loc - 1; // Go on to next location.
}
A[loc + 1] = temp; // Put temp in last vacated space.
}
}
I want to try this to print the result, so I modify this code to :
public class InsertionSort {
public static void main(String[] args) {
int[] A = {2, 7, 1, 9, 5, 12, 3};
insertionSort(A);
}
static void insertionSort(int[] A) {
// Sort the array A into increasing order.
int itemsSorted; // Number of items that have been sorted so far.
for (itemsSorted = 1; itemsSorted < A.length; itemsSorted++) {
// Assume that items A[0], A[1], ... A[itemsSorted-1]
// have already been sorted. Insert A[itemsSorted]
// into the sorted part of the list.
int temp = A[itemsSorted]; // The item to be inserted.
int loc = itemsSorted - 1; // Start at end of list.
while (loc >= 0 && A[loc] > temp) {
A[loc + 1] = A[loc]; // Bump item from A[loc] up to loc+1.
loc = loc - 1; // Go on to next location.
}
A[loc + 1] = temp; // Put temp in last vacated space.
}
for (int i=0; i <= A.length; i++){
TextIO.putln(A[i]);
}
}
}
But, it was give me this :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at InsertionSort.insertionSort(InsertionSort.java:33)
at InsertionSort.main(InsertionSort.java:6)
1
2
3
5
7
9
12
What is the mean of this error notification ?
exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at InsertionSort.insertionSort(InsertionSort.java:33)
at InsertionSort.main(InsertionSort.java:6)
Thank you