I’m trying to make the Bubble sort, and this is my code:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
double[] test = new double[5];
double t;
//Set random value to each of elements
for(int i = 0;i<test.length;i++){
test[i] = Math.round((100*Math.random()));
System.out.println(test[i]);
}
//Bubble Sort
for(int i = 0;i<test.length;i++){
for(int k = 0;k<test.length-1;k++){
int x = i+1;
if(test[i]>test[x]){
t = test[i];
test[i] = test[x];
test[x] = t;
}
}
}
}
}
But then I launch it, it throws an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Main.main(Main.java:24)
igoes up to the length of the array, and then you setxto go one past that! So, you try to access an element past the end of the array.You can either use
i < test.length - 1in the sort code, or otherwise check to make sure you don’t try to swap the last element with the element after it.