在二进制搜索中,我们对中间进行综合

时间:2017-06-04 10:40:57

标签: search binary

当低=中等时,我们改变m = l +(h-l + 1)/ 2.我怀疑是为什么我们采取低=中。

1 个答案:

答案 0 :(得分:0)

如果你的意思是l+h是奇数的情况,它将自动舍入,你不需要任何显式代码来舍入mid。这里是二分搜索算法。

给定具有值或记录A0 ... An-1的n个元素的数组A,排序使得A0≤...≤An-1和目标值T,以下子例程使用二进制搜索来查找索引A中的T [7]

Set L to 0 and R to n − 1.
If L > R, the search terminates as unsuccessful.
Set m (the position of the middle element) to the floor (the largest previous integer) of (L + R) / 2.
If Am < T, set L to m + 1 and go to step 2.
If Am > T, set R to m – 1 and go to step 2.
Now Am = T, the search is done; return m.

你永远找不到像m=l+(h-l+1)/2

这样的东西