解题思路
采用中分方法进行查找,考虑到是循环有序的数组,存在一边有序的情况,将中间值与最左边值比较,查看是否有序,则左有序,否则就是右有序。然后再确定待查找值的区域。
c++代码
//loopBuffer:循环有序数组
//length:循环有序数组长度
//value:待查找的数
//return:返回待查找数在数组中的位置
int BinarySearch(int* loopBuffer,int length, int value)
{
if(loopBuffer == NULL || length == 0)
{
cout<<"buffer is error"<<endl;
return -1;
}
int left = 0;
int right = length -1;
int mid = (left+right)/2;
while(left <= right)
{
mid = (left+right)/2;
if(value == loopBuffer[mid])
{
return mid;
}
if(loopBuffer[left]<loopBuffer[mid])//左有序
{
if(loopBuffer[left]<= value && value <= loopBuffer[mid])
{
right = mid - 1;
}
else
{
left = mid +1;
}
}
else //右有序
{
if(loopBuffer[mid] <= value && value <= loopBuffer[right])
{
left = mid+1;
}
else
{
right = mid-1;
}
}
}
return -1;
}
测试代码
int _tmain(int argc, _TCHAR* argv[])
{
int loopBuffer[10] = {6,7,8,9,0,1,2,3,4,5};
int i = 0;
int value = 0;
while(i < 10)
{
cout<<"please input a value in {6,7,8,9,0,1,2,3,4,5}:"<<endl;
cin>>value;
cout<<"pos = "<<BinarySearch(loopBuffer,10,value)<<endl;
i++;
}
cout<<"please input a value not in {6,7,8,9,0,1,2,3,4,5}:"<<endl;
cin>>value;
cout<<"pos = "<<BinarySearch(loopBuffer,10,value)<<endl;
return 0;
}