二进制搜索的时间复杂性是什么,它可以呼叫另一个辅助功能?

发布于 2025-01-30 15:12:22 字数 592 浏览 1 评论 0原文

助手检索要在搜索功能中进行比较的值。这里是一个对象。

def get_val(mem, c):    
  if c == "n":
    return mem.get_name()     
  elif c == "z":
    return mem.get_zip() 

在下面的辅助函数下面的函数中,每次迭代中都调用。这将影响二进制搜索的时间复杂性,还是仍然是O(log n)

def bin_search(array, c, s): 
  first = 0
  last = len(array)-1
  found = False
  while( first<=last and not found):
    mid = (first + last)//2
    val = get_val(array[mid], criteria)
    if val == s:
      return array[mid]
    else:
      if s < val:
        last = mid - 1
      else:
        first = mid + 1 
  return None

The helper retrieves value to be compared in the search function. here mem is an object.

def get_val(mem, c):    
  if c == "n":
    return mem.get_name()     
  elif c == "z":
    return mem.get_zip() 

In the function below the helper function above is called in each iteration. Will this impact the time-complexity of the binary search or will it still be O(log n)

def bin_search(array, c, s): 
  first = 0
  last = len(array)-1
  found = False
  while( first<=last and not found):
    mid = (first + last)//2
    val = get_val(array[mid], criteria)
    if val == s:
      return array[mid]
    else:
      if s < val:
        last = mid - 1
      else:
        first = mid + 1 
  return None

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小苏打饼 2025-02-06 15:12:22

由于您正在调用get_val()根据二进制搜索的迭代一次,因此总的时间复杂性应为

o(log n * f(x))

其中 f(x)get_val()的时间复杂性。如果这是恒定的(不取决于输入,例如array的内容),则实际上您的总时间复杂性仍然是 o(log n)

Since you are calling get_val() once per iteration of your binary search, the total time complexity should be

O(log n * f(x)),

where f(x) is the time complexity of get_val(). If this is constant (does not depend on the input, such as the contents of array), then indeed your total time complexity is still O(log n).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文