java - 检查数组是否已排序,返回 true 或 false

标签 java arrays sorting traversal

我正在编写一个简单的程序,如果对数组进行排序则返回 true 否则返回 false 并且我在 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));   
}

最佳答案

让我们看一下您构建的循环的更简洁版本:

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]第一次不是假的;因此,它实际上并不检查数组是否已排序!相反,它只检查前两个条目是否已排序。

一个具有类似逻辑但检查数组是否真的排序的函数是

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.
}

关于java - 检查数组是否已排序,返回 true 或 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19458278/

相关文章:

java - 如何从适配器Android调用 fragment 中的方法

Ruby:有条件地更改数组中的最后一个元素

c++ - 找出数字之间的最大差异

php - 按推荐人排序(相当复杂)

sorting - 如何在 clojure 中根据另一个向量的值对一个向量进行排序

java - JPA - 一对多 - 重复键值错误

Java 自动向量化

java - 必须选择好接口(interface)名称

php - 在多维数组中填充值 (PHP)

c# - 增量运算符如何与数组一起使用?