0

我今天在课堂上有一个关于冒泡排序的教程,但我遇到了一个不知道如何解决的错误。

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 8 在 BubbleSorter.main(BubbleSorter.java:24)

它没有被评估,但我想通过它继续下去。谢谢你。下面是我的全部代码。

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

4 回答 4

7

你有一个小错误:

这:

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

应该:

//                              v - Semicolon removed
for (i = 0; i<array.length; i++)
    System.out.print(array[i] + " ");
于 2013-02-19T15:15:39.940 回答
2

也改变

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

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

您遗漏了数组的最后一个元素!

输出

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
于 2013-02-19T15:19:26.473 回答
0

您需要更改 2 行

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

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

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

for (j = 1; j < (length); j++) {
于 2013-02-19T15:22:14.060 回答
0

在第 18 行,你需要去掉 ; 或放在括号中{

于 2013-02-19T15:26:49.817 回答