让我们看一下你构建的循环的更简洁版本:
for (i = 0; i < a.length; i++); {
if (a[i] < a[i + 1]) {
return true;
}
else {
return false;
}
}
我应该首先指出原始循环中的语法错误.也就是说,在大括号({)之前有一个分号(;),用于启动循环体.应删除该分号.
另请注意,我重新格式化了代码的空白区域,使其更具可读性.
现在让我们讨论循环中发生的事情.循环迭代器我从0开始并以a.length结束 – 1.因为我作为数组的索引起作用,所以指出a [0]是第一个元素和[a.length – 1]是有意义的数组的最后一个元素.但是,在循环体中,您还编写了索引i 1.这意味着如果i等于a.length – 1,则索引等于a.length,它超出了数组的范围.
函数isSorted也有相当大的问题,因为它在第一次返回时为真[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.
}