Search code examples
javaarraysexceptionbubble-sort

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

Solution

  • 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] + " ");