I am trying to make an array sorter. But I get an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
I don't know how to fix it. If I delete the line with the arrow then the code works, but then it doesn't swap. What did I do wrong?
Thanks for your help!
public class Main {
public static void main(String[] args) {
int[] list = {5, 3, 7, 2, 4, 8};
for (int i = 0; i < list.length; i = i + 2) {
if (i != list.length - 1) {
if (list[i] > list[i + 1]) {
int leftNumber = list[i];
int rightNumber = list[i + 1];
int src = i;
int temp = list[i];
list[i] = list[i + 1];
//--> list[i + 1] = list[temp];
System.out.println(leftNumber + " : " + rightNumber);
System.out.println(i + " : " + (i + 1));
System.out.println(Arrays.toString(list));
} else {
System.out.println("Good!");
}
}
}
}
}