The first part of the if
(the "ascending" check) is wrong, it should be:
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 single pair of numbers that do not hold the ascending-or-descending property, and only return true
after the loop exits.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…