|
|
|
|
|
by linknoid
2004 days ago
|
|
Usually when I'm doing a binary search, I'm not searching over integers, so the comparison itself will be quite expensive compared to the rest of the loop, so I prefer it like this: int BinarySearch<t>(t[] array, t find, int min, int max, Comparer<t> comparer)
{
int mid = 0;
while (min <= max)
{
mid = (int)(((long)min + (long)max) / 2);
int compared = comparer.Compare(find, array[mid]);
if (compared > 0)
min = mid + 1;
else if (compared < 0)
max = mid - 1;
else
return mid;
}
return ~mid;
}
|
|
"Specifically, it fails if the sum of low and high is greater than the maximum positive int value (231 - 1). The sum overflows to a negative value, and the value stays negative when divided by two." -https://ai.googleblog.com/2006/06/extra-extra-read-all-about...