二分查找
特点:
T(n) = T(n/2 - 1) + c
时间复杂度O(lgn)
前提:需要已排序的集合
int binary_search(int *arr,int start,int end,int key)
{
if(start<end)
{
int middle = (start+end)/2;
if(arr[middle] == key) return middle;
if(key<arr[middle-1])
{
return binary_search(arr,start,middle-1,key);
}
else
return binary_search(arr,middle+1,end,key);
}
else
return arr[start] == key? start : -1;
}
案例:
给定n个整数的集合S和另一个整数x,该算法确定一个S中是否存在两个其和刚好的x的元素。
时间复杂度Θ(nlgn)+n⋅Θ(lgn)=Θ(nlgn).
bool search_two_elements(int *arr,int start,int end,int key)
{
merge_sort(arr,start,end);
for (int i = start; i < end; ++i) {
int find = binary_search(arr,i+1,end,key-arr[i]);
if(find!=-1)
{
return true;
}
}
}