让我们来看看您构建的循环的清洁版本:
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; ergo它实际上并不检查数组是否已排序!相反,它只检查前两个条目是否已排序。
有类似的逻辑功能,但它会检查该数组真的排序是
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.
}
通过您的代码发布异常 – Cruncher
运行。你有4个条目,它应该很简单。 “我”在某些时候将等于3,[3 + 1]会尝试访问什么? – cklab
检查你的索引范围 – 2013-10-18 20:15:08