让我们看一下您构建的循环的更简洁版本:
for (i = 0; i < a.length; i++); {
if (a[i] < a[i + 1]) {
return true;
}
else {
return false;
}
}
我应该首先指出原始循环中的语法错误。也就是说,在开始循环体的;
花括号 ( ) 之前有一个分号 ( )。{
应该删除该分号。另请注意,我重新格式化了代码的空白以使其更具可读性。
现在让我们讨论一下循环内部发生了什么。循环迭代器i
从 开始0
并结束于a.length - 1
。由于i
用作数组的索引,因此指出它a[0]
是数组的第一个元素和a[a.length - 1]
最后一个元素是有意义的。然而,在你的循环体中,你也写了一个索引i + 1
。这意味着如果i
等于a.length - 1
,则您的索引等于a.length
数组边界之外的索引。
该函数isSorted
也有相当大的问题,因为它第一次返回 true 而第一次不返回a[i] < a[i+1]
false;因此,它实际上并不检查数组是否已排序!相反,它只检查前两个条目是否已排序。
具有类似逻辑但检查数组是否确实已排序的函数是
public static boolean isSorted(int[] a) {
// Our strategy will be to compare every element to its successor.
// The array is considered unsorted
// if a successor has a greater value than its predecessor.
// If we reach the end of the loop without finding that the array is unsorted,
// then it must be sorted instead.
// Note that we are always comparing an element to its successor.
// Because of this, we can end the loop after comparing
// the second-last element to the last one.
// This means the loop iterator will end as an index of the second-last
// element of the array instead of the last one.
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false; // It is proven that the array is not sorted.
}
}
return true; // If this part has been reached, the array must be sorted.
}