Implementation of C lower_bound

后端 未结 8 1437
北恋
北恋 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: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)
    

提交回复
热议问题