繁体   English   中英

Java,冒泡排序,数组,线程“ main”中的异常错误

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

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

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

它尚未评估,但我想继续进行下去。 谢谢。 下面是我的整个代码。

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

您有一个小错误:

这个:

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

也改变

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

你需要换两行

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++) {

在第18行,您需要摆脱; 或放在括号中{

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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