I am using binary search to search a number from a sorted array of numbers in O(log(n)) time. My C function for search is as follows:
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);
}
Here size
is the size of array and search
is the number to search.
Is there any way to perform the search in less complexity then the above program?