Hi,
I’d like to know if the following solution is valid for problem 12.2 - base case (distinct elements)
public static int find(List A){
int left = 0;
int right = A.size()-1;
while(left <= right){
int middle = left + (right - left) / 2;
if (middle >=1 && middle <= A.size() -2 ){
if (A.get(middle).compareTo(A.get(middle-1))<0&&A.get(middle).compareTo(A.get(middle+1))<0){
return middle;}
else if (A.get(middle).compareTo(A.get(0))>0){
left=middle+1;
} else { right=middle-1;}
}}
return -1;
}
Basically, if the middle element is the smallest element in the cyclically sorted list, this is it.
Otherwise, if the value of the middle element is bigger than the value of the starting index, we have to search to the right of the middle; if the value of the middle element is smaller than the value of the starting index, we have to search to the left of the middle.