4

I need to check if array was sorted strictly descendant. I wrote following code

public boolean isSortedDescendant(int [] array){
    if ((array.length == 0) || (array.length == 1)) {
        return true;
    } else {
        for(int i = 0; i < array.length - 1; i++){
            if (array[i] > array[i + 1]) {
                return true;
            }
        }
        return false;
    }
}

But it not working correctly. for

   int[] array2 = {3, 2, 2};

at least. I spend a lot of time for different approaches, but without any luck.

3
  • 3
    Your code can return true on the first i - how do you know the entire array is correct by only checking the first pair? Commented Feb 11, 2018 at 13:02
  • Loop is being breaking after first return? Commented Feb 11, 2018 at 13:07
  • (The synonym of descending is descendent (which is used where descendant may be - word usage is neither reflexive nor transitive).) Commented Feb 11, 2018 at 13:17

1 Answer 1

7

You should only return true after checking all the pair of elements:

public boolean isSortedDescendant(int [] array){
    if ((array.length == 0) || (array.length == 1)) {
        return true;
    } else {
        for(int i = 0; i < array.length - 1; i++){
            if (array[i] <= array[i + 1]) {
                return false;
            }
        }
        return true;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

It should be enough to follow for (int i = 1 ; i < array.length; i++) if (array[i-1] < array[i]) return false; with return true; (no for explicit special cases or using else where if always returns).
Thanks. but need little fix if (array[i] <= array[i + 1]) {
(Oops - just noted strictly in the question: "we" need to include equality as a reason to return false.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.