This implements binary search on an array of cstrings. One thing I'm wondering about is it faster or slower to pass a variable as const i.e. len. Also strcmp() gets called a lot and since I can't find any specific details on how it works, is it worthwhile to make my own function? For example does it immediately return a value if the first character of each arguments are different?
/*
*IN: scope: array of cstrings to be searched
*IN: len: length of array
*IN: find: cstring to be found
*OUT: true if find is in scope, otherwise false
*/
bool binSrch(char** scope, const int len, char* find)
{
int c, first, last, middle;
first = 0;
last = len - 1;
middle = (first+last)/2;
while( first <= last )
{
if (strcmp(scope[middle], find) < 0 )
first = middle + 1;
else if (strcmp(scope[middle], find) == 0)
{
return true;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
return false;
}
EDIT: is there a way to intelligently choose the pivot point? For example if your looking in a phone book for a name starting with Z you wouldn't start at the middle you'd start closer to the back.