Reputation: 53
I have been learning insertion sort currently, 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 am wrong.
Upvotes: 3
Views: 63
Reputation: 4458
According to the error status, it shows the error is on the
a[j] = term
So if you look at this closely you can see that while loop causes the ArrayIndexOutofBoundsException. So you can write the code like this:
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;
}
Upvotes: 2
Reputation: 2327
Reading the stack trace indicates that the error occurs on line
a[j]=term;
Looking up, you can see that the while loop ends when j<0; therefore, you must be getting this error because j=-1. Experimentation reveals that your code works if you add j++;
between the while and a[j]=term;
Upvotes: 2