算法:BINARYSEARCHREC
伪代码如下:
输入:按非降序排列的n个元素的数组A[1...n]和元素x
输出:如果x=A[j],则输出j,否则输出0
binarysearch(1,n)
binarysearch(low,high)
if low>high then return 0
else
mid ←(low+high)/2
if x=A[mid] then return mid
else if x<a[mid] then return binarysearch(low,mid-1)
else return binarysearch(mid+1,high)
end if
时间复杂度为:Ο(logn)
详细代码如下:
int binary_search_recursion(const int array[], int low, int high, int key)
{
int mid = low + (high - low)/2;
if(low > high)
return -1;
else{
if(array[mid] == key)
return mid;
else if(array[mid] > key)
return binary_search_recursion(array, low, mid-1, key);
else
return binary_search_recursion(array, mid+1, high, key);
}
}