Verificando se uma matriz é classificada em Java

Verificando se uma matriz é classificada em Java

1. Visão geral

Neste tutorial, veremos maneiras diferentes de verificar se uma matriz está classificada.

Antes de começar, entretanto, seria interessante verificarhow to sort arrays in Java.

2. Com um loop

Uma maneira de verificar é com um loopfor. Podemositerate all the values of the array one by one.

Vamos ver como fazer.

2.1. Matriz primitiva

Simplificando, vamos iterar todas as posições, exceto a última. Isso ocorre porque vamos comparar uma posição com a próxima.

Se alguns deles não forem classificados, o método retornaráfalse.. Se nenhuma das comparações retornarfalse,, significa que uma matriz está classificada:

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. Objetos que implementamComparable

Podemos fazer algo semelhante com objetos que implementamComparable. Em vez de usar um sinal de maior que,we’ll use 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. Objetos que não implementamComparable

Mas, e se nossos objetos não implementaremComparable? Neste caso, podemos, em vez disso,create a Comparator.

Neste exemplo, vamos usar o objetoEmployee. É um POJO simples com três campos:

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

    // getters and setters
}

Então, precisamos escolher em qual campo queremos ordenar. Aqui, vamos ordenar pelo campoage:

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

E então, podemos mudar nosso método para também obter umComparator:

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

Podemos, é claro, usarrecursion em vez disso. A ideia aqui é que vamos verificar duas posições na matriz e, em seguida, recursar até verificarmos todas as posições.

3.1. Matriz primitiva

Neste método,we check the last two positions. If they’re sorted, we’ll call the method again but with a previous position. Se uma dessas posições não for classificada, o método retornará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. Objetos que implementamComparable

Agora, vamos olhar novamente como objetos que implementamComparable. . Veremos que a mesma abordagem comcompareTo funcionará:

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. Objetos que não implementamComparable

Ultimamente, vamos tentar nosso objetoEmployee novamente, adicionando o parâmetroComparator :

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. Conclusão

Neste tutorial, vimos como verificar se uma matriz está classificada ou não. Vimos soluções iterativas e recursivas.

Nossa recomendação é usar a solução de loop. É mais limpo e fácil de ler.

Como de costume, o código-fonte deste tutorial pode ser encontradoover on GitHub.