Java - 检查数组是否是已排序的后代

Dmi*_*lov 4 java sorting algorithm

我需要检查数组是否严格排序后代.我写了以下代码

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但它无法正常工作.对于

   int[] array2 = {3, 2, 2};
Run Code Online (Sandbox Code Playgroud)

至少.我花了很多时间用于不同的方法,但没有任何运气.

Era*_*ran 7

只有在检查完所有元素后才能返回true:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它应该足够遵循`for(int i = 1; i <array.length; i ++)if(array [i-1] <array [i])return false;`with` return true;`(no for explicit特殊情况或使用`else`,其中`if`总是`return`s). (2认同)