Search code examples
javasortingcomparable

Java method to confirm the sorting works


I have an array of 100 ints (from 0 to 99) and I implement a Comparable interface. My task now is to confirm that sorting works (even though I know it does). My code is:

public static boolean confirmSorting(Guppy[] sortedArrayOfGuppies) {
    boolean confirmed = false;
    int maximumID = Integer.MAX_VALUE;
    for (Guppy guppy : sortedArrayOfGuppies) {
        if (guppy.getIdentificationNumber() < maximumID) {
            maximumID = guppy.getIdentificationNumber();
            confirmed = true;
        }
    }
    return confirmed;
}

But it returns true even for unsorted arrays. How do I make sure that iterate through every single object in my array?

Unfortunately, the solution proposed in How to check if array is already sorted doesn't work, not all ints are unique (some are the same)


Solution

  • Assume they are in sorted order first. Then return as soon as you find ones that aren't. No need to keep checking upon encountering the first failure. This does a simple verification and does not print any information. It returns true if sorted in ascending order and false otherwise. It also presumes the id number is an int.

    public static boolean confirmSorting(Guppy[] sortedArrayOfGuppies) {
        for (int i = 0; i < sortedArrayOfGuppies.length-1; i++) {
            int id1 = sortedArrayOfGuppies[i].getIdentificationNumber();
            int id2 = sortedArrayOfGuppies[i+1].getIdentificationNumber();
            if (id1 > id2) {
                return false;
            }
        }
        return true;
    }
    

    Note that you may want to pass in a comparator or flag so you can verify both ascending and descending sorts.