著名的二分查找的BUG
int binarySearch(int a[], int key, int length)
{
int low = 0;
int high = length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid;// key found
}
return -(low + 1);// key not found
}
是在其他地方无意间看到这个BUG的。这个BUG曾经存在于JDK中,参见这里
(需FQ)
看不出来BUG在哪里?
int mid = (low + high) / 2;
int midVal = a[mid];
如果low+high超过了int4个字节所能表示的最大数,会造成溢出。
解决方案是
int mid = low+((high-low) / 2);