应用条件:有序的线性表,对特定元素查找,只反馈单一元素
实现方法:1)递归
? ? ? ? ? ? ? ? ? 2)嵌套循环
以递归为例
int binarySearch(int* nums, int target, int right, int left)
{
if(right<left)
return -1;
int mid = (right+left)/2;
if(nums[mid] == target)
return mid;
if(nums[mid]<target)
return binarySearch(nums,target,right,mid+1);
else
return binarySearch(nums,target,mid-1,left);
}
int search(int* nums, int numsSize, int target)
{
return binarySearch(nums,target,numsSize-1,0);
}