为什么我们使用 mid = low + (high – low)/2;但不是 mid = (low/2) +(high /2)?
Why do we use mid = low + (high – low)/2; but not mid = (low/2) +(high /2)?
在二分查找中,我们使用mid = low + (high – low)/2
代替(low + high)/2
来避免溢出,但是不能分别计算low/2
和high/2
然后求和而不是 low+(( high-low)/2)
?
P.S。如果 low + (high – low)/2
更有效,那为什么会这样呢?
Can't we calculate low/2
and high/2
separately and then sum them up rather than using low+((high-low)/2)
?
当然可以。
If low+(high-low)/2
is more efficient, then why is it so?
对于很多硬件来说,除法比加减法慢,所以两次除法可能比使用更多加减法的方法慢。
假设 low 和 high 都是 3;那么middle = 3/2 + 3/2 = 1+1 = 2,其实是很糟糕的。 :-)
我们不使用 middle=high/2+low/2 的原因是它给了我们错误的结果
在二分查找中,我们使用mid = low + (high – low)/2
代替(low + high)/2
来避免溢出,但是不能分别计算low/2
和high/2
然后求和而不是 low+(( high-low)/2)
?
P.S。如果 low + (high – low)/2
更有效,那为什么会这样呢?
Can't we calculate
low/2
andhigh/2
separately and then sum them up rather than usinglow+((high-low)/2)
?
当然可以。
If
low+(high-low)/2
is more efficient, then why is it so?
对于很多硬件来说,除法比加减法慢,所以两次除法可能比使用更多加减法的方法慢。
假设 low 和 high 都是 3;那么middle = 3/2 + 3/2 = 1+1 = 2,其实是很糟糕的。 :-)
我们不使用 middle=high/2+low/2 的原因是它给了我们错误的结果