Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Check if array is sorted descendant

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.

like image 666
Dmitry Sokolov Avatar asked Mar 07 '23 22:03

Dmitry Sokolov


1 Answers

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;
    }
}
like image 61
Eran Avatar answered Mar 16 '23 13:03

Eran