A sequence is bitonic if it monotonically increases and then monotonically de- creases, or if it can be circularly shifted to monotonically increase and
Here is an efficient and simple implementation in Java. It traverses the array only once to determine whether the array is bitonic or not. It uses a variable reversal that counts the number of direction reversals of monotonicity in the array (including the circular wrapping around).
The variable trend can have three values:
0, if the values are the same;1, if the array is monotonically increasing;-1, if the array is monotonically decreasing.public static boolean bitonic(int[] arr) {
int reversal = 0;
int len = arr.length;
int trend = 0; // 0 means any, 1 means increasing, -1 means decreasing
for (int i= 0; i < len ; i++) {
if(arr[i%len] < arr[(i+1)%len]){
if (trend == 0) trend = 1;
else if ( trend == -1) {
reversal ++;
trend = 1;
}
}
else if(arr[i%len] > arr[(i+1)%len]){
if (trend == 0) trend = -1;
else if ( trend == 1) {
reversal ++;
trend = -1;
}
}
if(reversal > 2) return false;
}
return true;
}