Java 检查数组的降序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18005437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking an array for descending order
提问by dmetal23
I am writing code to check if my array is in ascending or descending order. If the boolean 'ascending' is true, then I check if it is ascending. If it is false, then I check for descending. I need help checking whether the array is descending or not... I have the code to check ascending which is written below:
我正在编写代码来检查我的数组是升序还是降序。如果布尔值“升序”为真,那么我检查它是否为升序。如果它是假的,那么我检查降序。我需要帮助检查数组是否是降序的……我有检查升序的代码,如下所示:
protected boolean isSorted(boolean ascending) {
boolean result = false;
if (ascending) {
for (int i=0;i<data.length-1;i++) {
if(data[i] < data[i+1]) {
result = true;
} else if(data[i] > data[i+1]) {
result = false;
}
}
} else {
//code to check for descending order
}
}
采纳答案by óscar López
The first part of the if(the "ascending" check) is wrong, it should be:
if(“升序”检查)的第一部分是错误的,应该是:
for (int i = 0; i < data.length-1; i++) {
if (data[i] > data[i+1]) {
return false;
}
}
return true;
Conversely, the descending check should be (and notice that it's enough to change the direction of the comparison operator):
相反,降序检查应该是(并注意改变比较运算符的方向就足够了):
for (int i = 0; i < data.length-1; i++) {
if (data[i] < data[i+1]) {
return false;
}
}
return true;
In both cases, you have to break out of the loop as soon as you find a singlepair of numbers that do not hold the ascending-or-descending property, and only return trueafter the loop exits.
在这两种情况下,你必须跳出循环只要你找到一个单一的对不保持上升,或递降性质的数字,而只返回true退出循环之后。
回答by Lee Meador
You can cheat and do it in one loop if you like and remove one addition:
如果您愿意,您可以作弊并在一个循环中完成并删除一个添加项:
protected boolean isSorted(boolean ascending) {
for (int i = 1; i < data.length; i++) {
if (data[i-1] == data[i]) {
continue;
}
if ((data[i-1] > data[i]) == ascending) {
return false;
}
}
return true;
}
NOTE: I am building on the code by @OscarLopez so upvote his if you upvote mine.
注意:我是在@OscarLopez 的代码基础上构建的,所以如果你对我的投赞成票,请投他的票。
回答by Amit Dhawan
To check if ArrayList<Integer>is in descending order try this:
要检查是否ArrayList<Integer>按降序排列,请尝试以下操作:
boolean isSorted(ArrayList<Integer> list){
boolean sorted = true;
for (int i = 1; i < list.size(); i++) {
if (list.get(i-1) >= (list.get(i)) ) {
sorted = true;
} else {
return false;
} // if else ends
} // for "i" ends
return sorted;
}

