mercredi 18 décembre 2019

java bubble sort if statement out of bounds

im having trouble running bubble sort, it shows no syntax errors and whenever i run it shows an java.lang.ArrayIndexOutOfBoundsException on line 13 which is the if statement,

import java.util.*;

public class Array3 {

public static void main(String[] args) {


    int[] numbers = {1, 5, 2, 6, 3, 8, 9, 4, 7};
    int temp = 0;       


    for(int i = 0 ; i <= numbers.length - 1 ; i++) {                        
        for (int j = 0 ; j <= numbers.length - 1 - i; j++) {
            if(numbers[j] > numbers[j + 1]) { //error is in this line
                temp = numbers[j];
                numbers[j] = numbers[j + 1];
                numbers[j + 1] = temp;
            }
        }
    }
    for(int i = 0 ; i <= numbers.length ; i++) {
        System.out.print(numbers + ", ");
    }
}

}

Aucun commentaire:

Enregistrer un commentaire