https://thebittheories.com/the-curious-case-of-binary-search-the-famous-bug-that-remained-undetected-for-20-years-973e89fc212
When calculating the mid position in the array
This operation can result in a overflow problem when low + high is too much high
mid = (low + high) / 2;
Replacing by this operation we no longer have the same problem
mid = low + (high - low)/2;
.............................................
Other example of overflow problem
int x = 256;
int y = 256;
unsigned long result;
result = x * 256 * 256 + y*256*256;
the result of the operation will be calculated with size of the highest operand that is integer, and 256 * 256 is already the maximum value of a integer, multiplied by an integer with value 256, the result will not fit in Integer space.
To fix this, we increase the size of the highest operando
result = x * 256 * 256ul + y*256*256ul;
or
result = ((unsigned long)x) * 256 * 256 + ((unsigned long)y)*256*256;
No comments:
Post a Comment