I was doing this shorting program of selection short and when I run it I got this exception which I am unable to figure out why I am having it, (the software I am using is Eclipse) here is the code
Scanner sc = new Scanner(System.in);
System.out.println("Enter the length of matrix");
int len=sc.nextInt();
int a[]=new int[len];
System.out.println("Enter the series");
for(int k=0; k<len; k++) {
a[k] = sc.nextInt();
}
for(int i=0;i<len-1;i++) {
int minind=i;
for(int j=0; j<len-1-i; j++) {
if(a[j] < a[minind]) {
minind=j;
}
int temp=a[i];
a[i]=a[minind];
a[minind]=a[temp];
}
}
System.out.println("Shorted array is ");
for(int item : a) {
System.out.print(item + " ");
}
here is my input
Enter the length of matrix
4
Enter the series
4 5 6 1
here is the exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at arrays.Selection_short.main(Selection_short.java:27)
Change below line and try.
a[minind]=a[temp];
to
a[minind]=temp;
Let me know if this solved ArrayIndexOutofBoundException.