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)
至少.我花了很多时间用于不同的方法,但没有任何运气.
只有在检查完所有元素后才能返回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)