看左右哪部分能完全有序,在决定区间划分
#include<cstdio>
int get_loop_array_index(int a[], int len, int key)
{
int left = 0, right = len - 1, mid;
while(left <= right)
{
mid = (left + right) >> 1;
if(a[mid] == key)
return mid;
if(a[left] <= a[mid])//左面有序
{
if(a[left] <= key && a[mid] >= key)//数字在左区间内
right = mid - 1;
else
left = mid + 1;
}
else
{
if(a[mid] <= key && a[right] >= key)
left = mid + 1;
else
right = mid - 1;
}
}
return -1;//不存在
}
int main()
{
int a[] = {4,5,6,7,8,1,2,3};
printf("%d\n", get_loop_array_index(a, 8, 2));
}