我正在使用二进制搜索在 O(log(n)) 时间内从排序的数字数组中搜索一个数字。我的搜索 C 函数如下:
search(int array[],int size,int search)
{
int first=0;
int last=size-1;
int middle = (first+last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
printf("Not found! %d is not present in the list.\n", search);
}
这size
是数组的大小,search
是要搜索的数字。有没有办法以比上述程序更复杂的方式执行搜索?