when I run the following program which is to create a random array of integers and then sort them in www.jdoodle.com, I get this error message:
arr = [18, 85, 93, 81, 8, 7, 18, 26, 46, 41, 69, 48, 50, 16, 3, 26, 27, '\nā 31, 47, 71]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at Sort.sortArray(Sort.java:35)
at Sort.main(Sort.java:10)
Command exited with non-zero status 1
I just can't find this damn bug. Maybe some of you more experienced out there can take a look at the code? Thanks a lot!
=========================================================================
import java.util.Random;
import java.util.Arrays;
public class Sort {
public static void main(String[] args) {
int[] arr = createArray(20);
System.out.println("arr = " + java.util.Arrays.toString(arr));
int[] sortArr = sortArray(arr);
System.out.println("sorted arr = " + '\n'
java.util.Arrays.toString(sortArr));
}
public static int[] createArray(int l) {
int[] vektor = new int[l];
for(int i = 0; i < vektor.length; i++) {
java.util.Random r = new java.util.Random();
int n = r.nextInt(100);
vektor[i] = n;
}
return vektor;
}
public static int[] sortArray(int[] inArr) {
int a[] = inArr;
int i, j, min, help = 0;
int minPos = a.length;
for(i = 0; i < a.length; i++) {
min = a[i];
for(j = 1; j < a.length - i; j++) {
if(a[j] < min) {
minPos = j;
}
help = a[minPos]; // <--- Line 35
a[minPos] = a[i];
a[i] = help;
}
}
return a;
}
}