[英]Binary Search comparison
So I have some code which performs a binary search. 所以我有一些代码执行二进制搜索。 Why is it essential for L and U to be compared with
<=
. 为什么L和U必须与
<=
进行比较。 Would I not get the same result with <
? 我不能用
<
?得到相同的结果吗?
public static int bsearch(int t, List<Integer> A) {
int L = 0, U = A.size() - 1;
while (L <= U) { //******cant I just do: while(L<U) *****?
int M = (L + U) / 2;
if (A.get(M) < t) {
L = M + 1;
} else if (A.get(M) == t) {
return M;
} else {
U = M - 1;
}
}
return -1;
}
Here is an edge case where this would not work: a list of size 1. 这是一个边缘情况,这不起作用:大小为1的列表。
In this case, we would have L == U == 0
. 在这种情况下,我们将
L == U == 0
。 Even if that one element happened to be the one for which you are looking, because the while
condition is not satisfied with <
, your element is never found. 即使那个元素恰好是你正在寻找的元素,因为
while
条件不满足<
,你的元素永远不会被找到。
L
and U
may be better named L
and R
. L
和U
可能更好地命名为L
和R
They define the left and right extents of the unsearched section of the array. 它们定义了数组未搜索部分的左右范围。 If your search narrows down to a single element, then they will be equal, but in order to test that last element, the while condition must hold or else you will skip it.
如果你的搜索缩小到单个元素,那么它们将是相等的,但是为了测试最后一个元素,while条件必须保持,否则你将跳过它。
This is not only true in a list of one element. 这不仅适用于一个元素的列表。 For example, searching the list
{ 1, 2, 3 }
for the element 1
. 例如,在列表
{ 1, 2, 3 }
搜索元素1
。 You will check 2
, see that it's greater, reduce U
to 0, and then will need to check element 0
, which can only happen if you continue to check when L == U
. 你将检查
2
,看到它更大,将U
减少到0,然后需要检查元素0
,这只有在你继续检查L == U
时才会发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.