Find the first element in a sorted array that is greater than the target

后端 未结 8 568
青春惊慌失措
青春惊慌失措 2020-11-30 17:40

In a general binary search, we are looking for a value which appears in the array. Sometimes, however, we need to find the first element which is either greater or less than

8条回答
  •  感动是毒
    2020-11-30 18:09

    My following implementation uses condition bottom <= top which is different from the answer of @templatetypedef.

    int FirstElementGreaterThan(int n, const vector& values) {
      int B = 0, T = values.size() - 1, M = 0;
      while (B <= T) { // B strictly increases, T strictly decreases
        M = B + (T - B) / 2;
        if (values[M] <= n) { // all values at or before M are not the target
          B = M + 1;
        } else {
          T = M - 1;// search for other elements before M
        }
      }
      return T + 1;
    }
    

提交回复
热议问题