我有一些二分查找相关的代码。为什么比较L和U时必须使用<=
,而不是只用<
,这样做不会得到相同的结果吗?
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;
}