Checking If an Array Is Sorted in Java – 在Java中检查一个数组是否被排序

最后修改: 2019年 7月 25日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll see different ways to check if an array is sorted.

在本教程中,我们将看到检查一个数组是否排序的不同方法。

Before starting, though, it’d be interesting to check how to sort arrays in Java.

不过在开始之前,先看看如何在Java中对数组进行排序会很有意思。

2. With a Loop

2.有一个环形结构

One way to check is with a for loop. We can iterate all the values of the array one by one.

检查的一种方法是使用for 循环。我们可以逐一迭代数组中的所有值

Let’s see how to do it.

让我们看看如何做到这一点。

2.1. Primitive Array

2.1.原始阵列

Simply put, we’ll iterate over all positions but the last one. This is because we’re going to compare one position with the next one.

简单地说,我们将迭代所有的位置,但最后一个位置除外。这是因为我们要将一个位置与下一个位置进行比较。

If some of them are not sorted, the method will return false. If none of the comparisons return false, it means that an array is sorted:

如果其中一些没有被排序,该方法将返回false。如果没有一个比较返回false,这意味着一个数组已经被排序。

boolean isSorted(int[] array) {
    for (int i = 0; i < array.length - 1; i++) {
        if (array[i] > array[i + 1])
            return false;
    }
    return true;
}

2.2. Objects That Implement Comparable

2.2.实现Comparable的对象

We can do something similar with objects that implement Comparable. Instead of using a greater-than sign, we’ll use compareTo:

我们可以对实现Comparable的对象做类似的事情。我们不使用大于号,而是使用compareTo:。

boolean isSorted(Comparable[] array) {
    for (int i = 0; i < array.length - 1; ++i) {
        if (array[i].compareTo(array[i + 1]) > 0)
            return false;
    }
    return true;
}

2.3. Objects That Don’t Implement Comparable

2.3.没有实现Comparable的对象

But, what if our objects don’t implement Comparable? In this case, we can instead create a Comparator.

但是,如果我们的对象没有实现Comparable呢?在这种情况下,我们可以创建一个Comparator.

In this example, we’re going to use the Employee object. It’s a simple POJO with three fields:

在这个例子中,我们将使用Employee对象。它是一个简单的POJO,有三个字段。

public class Employee implements Serializable {
    private int id;
    private String name;
    private int age;

    // getters and setters
}

Then, we need to choose which field we want to order by. Here, let’s order by the age field:

然后,我们需要选择我们想按哪个字段排序。这里,让我们按年龄字段排序。

Comparator<Employee> byAge = Comparator.comparingInt(Employee::getAge);

And then, we can change our method to also take a Comparator:

然后,我们可以改变我们的方法,让它也接受一个Comparator

boolean isSorted(Object[] array, Comparator comparator) {
    for (int i = 0; i < array.length - 1; ++i) {
        if (comparator.compare(array[i], (array[i + 1])) > 0)
            return false;
    }

    return true;
}

3. Recursively

3.递归

We can, of course, use recursion instead. The idea here is we’ll check two positions in the array and then recurse until we’ve checked every position.

当然,我们可以使用递归代替。这里的想法是我们将检查数组中的两个位置,然后递归,直到我们检查完每个位置。

3.1. Primitive Array

3.1.原始阵列

In this method, we check the last two positions. If they’re sorted, we’ll call the method again but with a previous position. If one of these positions is not sorted, the method will return false:

在这个方法中,我们检查最后两个位置。如果它们被排序了,我们将再次调用该方法,但要用到之前的位置。如果其中一个位置没有被排序,该方法将返回false:

boolean isSorted(int[] array, int length) {
    if (array == null || length < 2) 
        return true; 
    if (array[length - 2] > array[length - 1])
        return false;
    return isSorted(array, length - 1);
}

3.2. Objects That Implement Comparable

3.2.实现Comparable的对象

Now, let’s look again as objects that implement Comparable. We’ll see that the same approach with compareTo will work:

现在,让我们再看看实现Comparable的对象。我们将看到,与compareTo相同的方法将起作用。

boolean isSorted(Comparable[] array, int length) {
    if (array == null || length < 2) 
        return true; 
    if (array[length - 2].compareTo(array[length - 1]) > 0)
        return false;
    return isSorted(array, length - 1);
}

3.3. Objects That Don’t Implement Comparable

3.3.没有实现Comparable的对象

Lately, let’s try our Employee object again, adding the Comparator parameter:

最近,让我们再次尝试我们的Employee对象,添加Comparator参数。

boolean isSorted(Object[] array, Comparator comparator, int length) {
    if (array == null || length < 2)
        return true;
    if (comparator.compare(array[length - 2], array[length - 1]) > 0)
        return false;
    return isSorted(array, comparator, length - 1);
}

4. Conclusion

4.总结

In this tutorial, we have seen how to check if an array is sorted or not. We saw both iterative and recursive solutions.

在本教程中,我们已经看到了如何检查一个数组是否被排序。我们看到了迭代和递归两种解决方案。

Our recommendation is to use the loop solution. It’s cleaner and easier to read.

我们的建议是使用循环解决方案。它更干净,更容易阅读。

As usual, the source code from this tutorial can be found over on GitHub.

像往常一样,本教程的源代码可以在GitHub上找到超过