use*_*463 12 java arrays sorting traversal
我正在编写一个简单的程序,如果一个数组被排序为false,则返回true,并且我在eclipse中不断得到一个异常,我只是想不通原因.我想知道是否有人可以看看我的代码并解释为什么我得到一个超出界限的数组异常.感谢您的高级帮助.
public static boolean isSorted(int[] a)
{
int i;
for(i = 0; i < a.length; i ++);{
if (a[i] < a[i+1]) {
return true;
} else {
return false;
}
}
}
public static void main(String[] args)
{
int ar[] = {3,5,6,7};
System.out.println(isSorted(ar));
}
Run Code Online (Sandbox Code Playgroud)
Ric*_*gle 32
让我们看一下你构建的循环的更简洁版本:
for (i = 0; i < a.length; i++); {
if (a[i] < a[i + 1]) {
return true;
}
else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我应该首先指出原始循环中的语法错误.也就是说,;在花括号()之前有一个分号(),{用于启动循环体.应该删除该分号.另请注意,我重新格式化了代码的空白区域,使其更具可读性.
现在让我们讨论循环中发生的事情.循环迭代器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.
}
Run Code Online (Sandbox Code Playgroud)
Jac*_* G. 10
对于使用 Java 8 及更高版本的任何人,这是一个简单的单行:
public static boolean isSorted(int[] array) {
return IntStream.range(0, array.length - 1).noneMatch(i -> array[i] > array[i + 1]);
}
Run Code Online (Sandbox Code Playgroud)
或者逻辑上等效的替代方案:
public static boolean isSorted(int[] array) {
return IntStream.range(0, array.length - 1).allMatch(i -> array[i] <= array[i + 1]);
}
Run Code Online (Sandbox Code Playgroud)