让我们看一下您构建的循环的更清晰版本:
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
该函数也存在相当大的问题,因为它第一次返回true,第一次返回false。因此,它实际上根本不检查数组是否已排序!相反,它只检查前两个条目是否排序。isSorted
a[i] < a[i+1]
具有类似逻辑但检查数组是否真正排序的函数是
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.
}