void * __cdecl bsearch (
REG4 const void *key,
const void *base,
size_t num,
size_t width,
int (__cdecl *compare)(const void *, const void *)
)
{
REG1 char *lo = (char *)base;
REG2 char *hi = (char *)base + (num - 1) * width;
REG3 char *mid;
unsigned int half;
int result;
while (lo <= hi)
if (half = num / 2)
{
mid = lo + (num & 1 ? half : (half - 1)) * width;
if (!(result = (*compare)(key,mid)))
return(mid);
else if (result < 0)
{
hi = mid - width;
num = num & 1 ? half : half-1; //当num为偶数时,mid下标实际为num/2 -1,
//因此当小于a[mid]时,num个数(也就是需要继续二分查找的元素个数,mid元素不再参与
)减少为原来一半少1.
}
else {
lo = mid + width;
num = half; //此处和上面不同,num是偶数与否不影响剩下的元素个数,始终为half = num/2个。 //
}
}
else if (num)
//只有1个元素(可能是数组本身只有一个元素,或者是二分查找后最后剩下1个元素)
return((*compare)(key,lo) ? NULL : lo);
else
break;
return(NULL);
}