非递归:
class Solution
{
public:
bool search(int A[], int n, int target)
{
int first = 0, last = n;
while (first != last)
{
const int mid = (first + last) / 2;
if (A[mid] == target)
return true;
if (A[first] < A[mid])
{
if (A[first] <= target && target < A[mid])
last = mid;
else
first = mid + 1;
}else if(A[first] > A[mid])
{
if (A[mid] < target && target <= A[last-1])
first = mid + 1;
else
last = mid;
}else{
first ++; //化归的思想,遇到A[first] == A[mid],就first++直到 把问题化归到I能够解决为止。
}
}
return false;
}
};
递归:
public://此递归方法I和II都适用,因为它只负责先从左边找然后右边找,无需考虑数组中数字的顺序,这就是递归。
bool binarysearch(int A[],int first,int last,int target){
int mid = (first + last)/2;
if(target == A[mid])
return true;
if(first == last - 1)
return false;
bool res = binarysearch(A,first,mid,target);
if(res == false)
res = binarysearch(A,mid,last,target);
return res;
}
bool search(int A[], int n, int target)
{
return binarysearch(A,0,n,target);
}
};