【问题标题】:Why does using enhanced for-loop for implementing bubble sort is giving me ArrayIndexOutOfBoundsException?为什么使用增强的 for 循环来实现冒泡排序会给我 ArrayIndexOutOfBoundsException?
【发布时间】:2015-09-10 03:13:50
【问题描述】:

我们都知道编码 for 循环需要很长时间才能输入。这就是为什么我尝试将我的长 for 循环转换为增强型 for 循环,但每次我编译我的代码时,我都拥有IndexOutOfBoundException

使用示例数组:

int[] 数组 = {5, 4, 3, 2, 1};

简单循环版本(工作代码)

public static int[] bubbleSort(int[] array) {
    for (int i = 0; i < array.length; i++) {
        for (int j = 1; j < array.length - i; j++) {
            if (array[j - 1] > array[j]) {
                int temp = array[j - 1];
                array[j - 1] = array[i];
                array[i] = temp;
            }
        }
    }
}

增强的 for 循环(不工作)

 public static int[] bubbleSort(int[] array) {
    for (int i : array) {
        for (int j : array) {
            if (array[j - 1] > array[j]) {
                int temp = array[j - 1];
                array[j - 1] = array[i];
                array[i] = temp;
            }
        }
    }
}

它给了我:

错误:java.lang.ArrayIndexOutOfBoundsException:5

【问题讨论】:

  • Fencepost 下界错误:0 而不是 1,所以 j-1 是 -1,这当然行不通。

标签: java arrays algorithm for-loop


【解决方案1】:

您误解了增强的for 循环。您获得的值是数组中的条目,而不是它们的索引。

这可能有助于澄清:

int[] foo = {10, 20, 30};
for (int n : foo) {
    System.out.println(n);
}

...将显示

10 20 30

不是

0 1 2

Live Example

增强的for 循环不适用于冒泡排序。

【讨论】:

    【解决方案2】:

    在枚举语法中:

    for(int i : numbers) {
        ....
    }
    

    i,而不是索引。因此,如果您的数组中有一个大于数组长度的值,您将获得ArrayIndexOutOfBoundsException

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2011-10-25
      • 2021-02-06
      • 2022-01-05
      • 2012-08-28
      • 2015-09-12
      • 2017-06-28
      相关资源
      最近更新 更多