I would like to determine is an array of numbers, is always increasing (for all x, x+1 >= x) or always decreasing (for all x, x+1 =< x). If so return true. Another way to state the problem is, return true if the array is sorted or reverse sorted. Here is the code:
public static boolean isAlwaysIncreasingOrDecreasing(int[] arr) {
//check if decreasing
int previous = arr[0];
boolean decreasing = true;
for(int i = 1; i < arr.length; i++) {
if(previous < arr[i]) {
decreasing = false;
break;
}
previous = arr[i];
}
//check if increasing
int previous = arr[0];
boolean increasing = true;
for(int i = 1; i < arr.length; i++) {
if(previous > arr[i]) {
increasing = false;
break;
}
previous = arr[i];
}
//return true if always increasing or decreasing
if(decreasing || increasing) {
return false;
}
return true;
}
Any tips? Obviously duplicate values are allowed, so inputs such as 1,2,3,3,3,3....3,4,2,5,6 would be tricky.
I ask mainly out of curiosity, as the above solution would take at most 2 iterations through the array and I don't think it is possible to take less than 1, so it's not too bad :)