【发布时间】: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