算法思路:
C语言解法:
//二分查找思想
int search(int* nums, int numsSize, int target){
if(numsSize == 0) return -1;
if(numsSize == 1) (target == nums[0]) ? 0 : -1;
int left = 0,right = numsSize-1;
while(left <= right) {//如果left==right,找到了说明结果是left,right本身.
//如果没找到就说明数组中没有那个元素。
//(因为此算法在缩小查找范围的时候就是往target方向找的,legt==right还没找到,就说明已经翻遍了还是找不到)
int mid = (left+right)/2;
if(nums[mid] == target) return mid;
if(nums[0] <= nums[mid]) { //左边有序
if(target >= nums[0] && target <= nums[mid]) { //target在左序列范围内
right = mid-1; //查找左边界
}
else left = mid+1; //查找右边界
}
else { //右边有序
if(target >= nums[mid] && target <= nums[numsSize-1]) { //target在右序列范围之内
left = mid + 1; //查找右边界
}
else right = mid-1; //查找左边界
}
}
return -1;
}