我找不到该问题的答案。我正在使用插入排序方法,但无法正确执行:
public static <T extends Comparable<? super T>> void insertionSort(T[] array) {
int length = array.length;
T temp;
for (int i = 1; i < length; i++) { //start of unsorted
temp = array[i]; //save the element
int j = i-1;
while (temp.compareTo(array[j]) < 0 && j >= 0) { // while temp is less than array[j]
array[j+1] = array[j];
j--;
} //end of while
array[j+1] = temp; //as soon as temp is greater than array[j], set array[j] equal to temp
}
}
这在while循环行上返回了
ArrayIndexOutOfBoundsException
,但是当我在while循环中将条件切换到此位置时:while (j >= 0 && temp.compareTo(array[j]) < 0)
有效。我不认为Java中的条件循环顺序对程序有影响吗?这对我来说很奇怪,因为在我使用
&&
的语句中从未见过或听说过顺序很重要,因为我假设两条while循环行是等效的。我一直想知道这有一段时间,但找不到答案。有人可以解释为什么会这样吗?
最佳答案
从左到右评估条件。
最初,对于案例j=-1
,您的代码没有评估第二个条件,因为第一个条件抛出了ArrayIndexOutOfBoundsException
异常。
while (temp.compareTo(array[j]) < 0 && j >= 0)
但是,当您切换这样的条件时:
while (j >= 0 && temp.compareTo(array[j]) < 0)
然后对于相同的情况(
j=-1
),由于第一个条件变为false
,因此无论第二个值如何,整个条件将始终为false;因此第二个条件将不会被评估,因此在这种情况下也不例外。