Binary Search Comparison

So, I have a code that does a binary search. Why for L and U it is necessary to compare with <=. Didn't I 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;
  }
+4
source share
2 answers

Here's an example of an edge where this would not work: a list of size 1.

In this case, we would have L == U == 0. Even if this one element turned out to be the one for which you are looking, because the condition is whilenot satisfied <, your element will never be found.

+3
source

L U L R. . , , while, .

. , { 1, 2, 3 } 1. 2, , , U 0, 0, , , L == U.

+2

Source: https://habr.com/ru/post/1687338/


All Articles