'Why do we use mid = low + (high – low)/2; but not mid = (low/2) +(high /2)?
In binary search, we use mid = low + (high – low)/2 instead of (low + high)/2 to avoid overflow, however, can't calculate low/2 and high/2 separately and then sum them up rather than low+(( high-low)/2)?
P.S. If low + (high – low)/2 is more efficient, then why is it so?
Solution 1:[1]
Can't we calculate
low/2andhigh/2separately and then sum them up rather than usinglow+((high-low)/2)?
Sure.
If
low+(high-low)/2is more efficient, then why is it so?
For a lot of hardware dividing is slower than adding and subtracting, so dividing twice might be slower than the method that uses more adding and subtracting.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matt Robin |
