Implementation of C lower_bound

后端 未结 8 1436
北恋
北恋 2020-12-12 18:48

Based on the following definition found here

Returns an iterator pointing to the first element in the sorted range [first,last) which does not com

相关标签:
8条回答
  • 2020-12-12 19:11

    lower_bound is almost like doing a usual binary search, except:

    1. If the element isn't found, you return your current place in the search, rather than returning some null value.
    2. If the element is found, you search leftward until you find a non-matching element. Then you return a pointer/iterator to the first matching element.

    Yes, it's really that simple. :-)

    0 讨论(0)
  • 2020-12-12 19:13

    The lower_bound and upper_bound functions in python would be implemented as follows:

    def binLowerBound(a, lo, hi, x):
      if (lo > hi):
        return hi
      mid = (lo + hi) / 2;
      if (a[mid] == x):
        return binLowerBound(a, lo, mid-1, x)
      elif (a[mid] > x):
        return binLowerBound(a, lo, mid-1, x)
      else:
        return binLowerBound(a, mid+1, hi, x)
    
    def binHigherBound(a, lo, hi, x):
      if (lo > hi):
        return lo
      mid = (lo + hi) / 2;
      if (a[mid] == x):
        return binHigherBound(a, mid+1, hi, x)
      elif (a[mid] > x):
        return binHigherBound(a, lo, mid-1, x)
      else:
        return binHigherBound(a, mid+1, hi, x)
    
    0 讨论(0)
提交回复
热议问题