Answer the question
In order to leave comments, you need to log in
Bug in bubble sort code?
I am new to Java. I'm trying to do bubble sort, I wrote the following 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;
//Присвоение каждому элементу случайного значения
for(int i = 0;i<test.length;i++){
test[i] = Math.round((100*Math.random()));
System.out.println(test[i]);
}
//Сортировка пузырьком
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;
}
}
}
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5<br/>
at Main.main(Main.java:24)
Answer the question
In order to leave comments, you need to log in
We look:
at the last iteration of the outer loop, test[x] will go beyond the boundaries of the array.
Because i is the index of the last element of test, and x = i+1 is the index of the one after the last...
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]){
.....
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question