简体   繁体   中英

What's wrong with my method that checks if an array of strings is sorted

I am doing a Java class and I cannot figure it out where I am wrong.

I have a class called ArrayMethods and a method that I must use to see if my arrays are sorted or not. This is my code:

public class ArrayMethods
{
    String[] list; //instance variable
    /**
     * Constructor for objects of class ArrayMethods
     */
    public ArrayMethods(String[] list)
    {
        // initialise instance variables
        this.list = list;
    }

    /**
     * Determines if the array is sorted (do not sort)
     * When Strings are sorted, they are in alphabetical order
     * Use the compareTo method to determine which string comes first
     * You can look at the String compareTo method in the Java API
     * @return true if the array  is sorted else false.
     */
    public boolean isSorted()
    {
        boolean sorted = true;

        // TODO: Write the code to loop through the array and determine that each
        // successive element is larger than the one before it
        for (int i = 0; i < list.length - 1; i++){
            if (list[i].compareTo(list[i + 1]) < 0){
                sorted = true;
            }
        }
        return sorted;
    }
}

And then I have a tester for this arrays that goes like this:

public class ArrayMethodsTester {
    public static void main(String[] args) {
        //set up
        String[] animals = {"ape", "dog", "zebra"};
        ArrayMethods zoo = new ArrayMethods(animals); 

        //test isSorted
        System.out.println(zoo.isSorted());
        System.out.println("Expected: true");

        String[] animals2 = {"ape", "dog", "zebra", "cat"};
        zoo = new ArrayMethods(animals2);         
        System.out.println(zoo.isSorted());
        System.out.println("Expected: false");

        String[] animals3 = {"cat", "ape", "dog", "zebra"};
        zoo = new ArrayMethods(animals3); ;
        System.out.println(zoo.isSorted());
        System.out.println("Expected: false");
    }
}

For the first array I do get true as it is normal, the problem is that I get true for the other 2 and it is clearly that this is false. What is it that I do not get?

could make it a little simpler by directly returning false inside of the loop

   for (int i = 0; i < list.length - 1; i++) {
        if (list[i].compareTo(list[i + 1]) > 0) {
            return false;
        }
    }
    return true;
public class ArrayMethods
{
    String[] list; //instance variable
    /**
     * Constructor for objects of class ArrayMethods
     */
    public ArrayMethods(String[] list)
    {
        // initialise instance variables
        this.list = list;
    }

    /**
     * Determines if the array is sorted (do not sort)
     * When Strings are sorted, they are in alphabetical order
     * Use the compareTo method to determine which string comes first
     * You can look at the String compareTo method in the Java API
     * @return true if the array  is sorted else false.
     */
    public boolean isSorted()
    {
        boolean sorted = true;

        // TODO: Write the code to loop through the array and determine that each
        // successive element is larger than the one before it
       for (int i = 0; i < list.length - 1; i++){
            if (list[i].compareTo(list[i + 1]) > 0){
                sorted = false;
                break;

            }
        }
        return sorted;
    }
}`

You could also do it with Java 8 streams if you like their syntax (though it is not a perfect use case for them because you need two elements of the stream for your operation):

public static boolean isSorted(final String[] array) {
    return !IntStream.range(1, array.length)
        .mapToObj(i -> new Pair<String>(array[i - 1], array[i])).parallel()
            .anyMatch(t -> t.first.compareTo(t.second) > 0);
}

The code uses a small helper class Pair

public static final class Pair<T> {
    final T first;
    final T second;

    private Pair(final T first, final T second) {
        this.first = first;
        this.second = second;
    }
}

This solution could also run parallel which would make it faster when running on large arrays.

Credits to Collect successive pairs from a stream for accessing a Pair of elements with streams

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM