Boolean method to check array is sorted in java

utopia :

I'm writing a method to check if an array of type double is numerically ascending in Java. However, I don't understand why I must swap where I place return true and return false for my code to work. Surely I can keep it as it is and it should still work? What am I not understanding?

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

Andronicus :

You're returning at the first if statement body invokation, which means, you're checking whether first two elements are sorted. You should rather return false, if there is a consecutive pair, that is not sorted. If you go through the whole array and no such pair is found, then the array is sorted. This should do the job:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360087&siteId=1