Given a range, calculating the mid is a straight forward process.
mid = (low + high) / 2;
But, there’s a problem with this line. Adding two large positive numbers can result in an overflow, if the sum is more than the max positive number.
One way to fix it is to use the following:
mid = low + ((high - low) / 2);
This’ll prevent the expression from overflowing to a negative value. I’ve read this line in random code so many times and wondered why anyone would want to write it this way instead of the simpler and more straight forward way I mentioned in the beginning of this blog. It wasn’t until I read this lovely blog post that I understood the reason behind it.
Comments