递归实现
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int res = dichotomySearch(nums,target,left,right);
return res;
}
public static int dichotomySearch(int[] nums,int target,int left, int right){
if(target < nums[left]||target > nums[right]||left > right)
return -1;
int center = (left + right)/2;
if(nums[center] > target){
return dichotomySearch(nums,target,left,center - 1);
}else if(nums[center] < target){
return dichotomySearch(nums,target,center + 1,right);
}else{
return center;
}
}
非递归实现
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left <= right){
int center = (left + right)/2;
if(nums[center] > target){
right = center - 1;
}else if(nums[center] < target){
left = center + 1;
}else{
return center;
}
}
return -1;
}