【发布时间】:2021-02-04 10:58:21
【问题描述】:
我一直在尝试在 Java 中实现插入排序,但在我的程序中遇到了一个奇怪的错误。进行插入的while 循环具有以下条件:
while (arr[j] > key && j>=0)
当j<0 时,循环因ArrayIndexOutOfBoundsException 而崩溃。我花了几个小时试图解决这个问题,但显然改变表达式的顺序解决了这个问题:
while (j >= 0 && arr[j] > key)
这种行为背后的原因是什么?
这是完整的代码:
//Insertion Sort
class Sort {
public int[] sort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = i - 1;
int key = arr[i];
while (arr[j] > key && j>=0) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
return arr;
}
}
public class InsertionSort {
public static void main(String[] args) {
System.out.println("THis is it");
int[] test = { 54, 68, 92, 3, 565, 8, 7, 64, 0 };
Sort lort = new Sort();
lort.sort(test);
for (int a : test)
System.out.println(a);
}
}
【问题讨论】:
-
您的意思是说第一个版本以
ArrayIndexOutOfBoundsException崩溃而第二个版本没有?这是有道理的。 -
@JohnKugelman 是的,你是对的。
标签: java