简体   繁体   中英

Java, Bubble Sort, Arrays, Exception in thread “main” Error

I have a tutorial in class today with bubble sort and I've got an error I don't know how to fix.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8 at BubbleSorter.main(BubbleSorter.java:24)

It is not assessed but I would like to get through it to continue on. Thank you. Below is my entire code.

public class BubbleSorter {
    public static void main(String[] args)
    {
        int i;
        int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };
        System.out.println("Array Values before the sort:\n");
        for (i = 0; i < array.length; i++)
            System.out.print(array[i] + " ");
        System.out.println();
        System.out.println();

        bubble_srt(array, array.length);

        System.out.print("Array Values after the sort:\n");
        for (i = 0; i < array.length; i++)
            ;
        System.out.print(array[i] + " ");
        System.out.println();
        System.out.println("PAUSE");
    }

    private static void bubble_srt(int[] array, int length) {
        int i, j, t = 0;
        for (i = 0; i < length; i++) {
            for (j = 1; j < (length - 1); j++) {
                if (array[j - 1] > array[j]) {
                    t = array[j - 1];
                    array[j - 1] = array[j];
                    array[j] = t;
                }
            }
        }
    }
}

You have a small mistake:

This:

for (i = 0; i<array.length; i++);
System.out.print(array[i] + " ");

should be:

//                              v - Semicolon removed
for (i = 0; i<array.length; i++)
    System.out.print(array[i] + " ");

Also change

for (j = 1; j < (length - 1); j++) {

to

for (j = 1; j < length; j++) {

You left out the last element of the Array!

Output

Array Values before the sort:

12 9 4 99 120 1 3 10 

Array Values after the sort:
1 3 4 9 10 12 99 120 
PAUSE

You need to change 2 lines

for (i = 0; i < array.length; i++)
        ;
System.out.print(array[i] + " ");

to

for (i = 0; i < array.length; i++)
    System.out.print(array[i] + " ");

and

for (j = 1; j < (length - 1); j++) {

to

for (j = 1; j < (length); j++) {

On line 18 you need to get rid of the ; or put in brackets {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM