B
B
bazeyvit2012-03-30 18:50:04
Java
bazeyvit, 2012-03-30 18:50:04

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;		
          
        }				
      }			
    }					
  }
}

And I get an error:
Exception in thread &quot;main&quot; java.lang.ArrayIndexOutOfBoundsException: 5<br/>
at Main.main(Main.java:24)

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
da0c, 2012-03-30
@bazeyvit

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]){
.....
}
}
}

B
bazeyvit, 2012-03-30
@bazeyvit

Already found errors:

  1. In

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question