utopia
utopia

Reputation: 51

Boolean method to check array is sorted in java

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;
}

Upvotes: 1

Views: 906

Answers (2)

Naman
Naman

Reputation: 31878

You can quote it as if any of the element is greater than its next element, the array is not sorted, which could be represented functionally as

public static boolean isSorted(double[] arr) {
    return !IntStream.range(0, arr.length - 1)
            .anyMatch(i -> arr[i] > arr[i + 1]);
}

In other words, for your array to be sorted you need to ensure, none of your elements should satisfy the condition that it is greater than the number next to in the array.

Hence, a better functional way of writing this would be:

public static boolean isSorted(double[] arr) {
    return IntStream.range(0, arr.length - 1)
            .noneMatch(i -> arr[i] > arr[i + 1]);
}

Upvotes: 2

Andronicus
Andronicus

Reputation: 26046

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;

Upvotes: 1

Related Questions