I am trying to locate the point of rotation in a sorted array through a modified binary search.
Consider this array int values[9]={7, 8, 9, 1, 2, 3, 4, 5, 6};
The point of rotation here is at index = 3 i.e at 9.
I wrote this function for the above operation.
void FindRotationPoint(int values[], int numvalues)
{
int first =0;
int last = numvalues-1;
int middle;
bool moreTosearch= (first<=last);
while(first<=last)
{
middle = (first+last)/2;
if(values[0]>values[middle]) //Keep looking right if the middle value in array is greater than first
{
last = middle-1;
}
if (values[0]<values[middle]) //Keep looking left if the middle value in array is less than first
{
first = middle+1;
}
}
cout<<middle+1<<endl;
cout<<values[middle];
}
If the elements are
int values[9]={7, 8, 9, 1, 2, 3, 4, 5, 6}; Output: 4, 1 (Wrong)
int values[9]={7, 8, 9, 10, 2, 3, 4, 5, 6}; Output: 4, 10 (Correct)
The point of rotation which is at an even place is found correct whereas in the other case, it finds the succeeding element. What am I missing in the above code?
This works: