Finding point of rotation in the sorted array
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开发者_如何学Go (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:
void FindRotationPoint(int values[], int numvalues)
{
int first =0;
int last = numvalues-1;
int middle=0;
bool moreTosearch= (first<=last);
while(first<last)
{
middle = (first+last)/2;
if(values[first]>=values[middle]) //Keep looking right if the middle value in array is greater than first
{
last = middle;
cout<<"first>middle: "<<first<<" "<<middle<<" "<<last<<"\n";
}
else if (values[middle]>=values[last]) //Keep looking left if the middle value in array is less than first
{
first = middle;
cout<<"middle<last: "<<first<<" "<<middle<<" "<<last<<"\n";
}
}
cout<<middle+1<<endl;
cout<<values[middle];
}
int main()
{
int values[9]={7, 8, 9, 1, 2, 3, 4, 5, 6};
FindRotationPoint(values, 9);
return 0;
}
void FindRotationPoint(int values[], int numvalues)
{
int first =0;
int last = numvalues-1;
int middle;
bool moreTosearch= (first<=last);
while(moreTosearch)
{
middle = (first+last)/2;
if(middle == first) break;
if(values[0]>values[middle]) //Keep looking right if the middle value in array is greater than first
{
last = middle;
moreTosearch= (first<=last);
}
if (values[0]<values[middle]) //Keep looking left if the middle value in array is less than first
{
first = middle;
moreTosearch= (first<=last);
}
}
}
This should work .
精彩评论