【问题标题】:How can I put this Binary Search to work?我怎样才能让这个二分搜索工作?
【发布时间】:2020-06-23 16:12:14
【问题描述】:

这段代码给了我一个错误:c 是一个列表或一个数组 // k = 是我们要检查的数字

def binary_search(c,k):
    low = 0
    high = len(c) - 1
    while low <= high:
        mid = floor((low + high) / 2)
        if c[mid] == k:
           return True
        elif c[mid] > k:
           high = mid - 1
        else:
           low = mid - 1
    return False 

这就是错误:File "C:/Users/JJ/OneDrive - ISCTE-IUL/EDA/Aula3.py", line 108, in binary_search mid = floor((low + high) / 2) KeyboardInterrupt

我不知道为什么会发生这种情况,所以我需要我能得到的所有帮助。谢谢你的时间

【问题讨论】:

  • KeyboardInterrupt 只是意味着您退出程序,例如Ctrl + C。我猜循环永远不会结束,因为low 越来越小。也许应该增加?
  • @FiddleStix OMG,谢谢!!!!!!它确实帮助了我很多..

标签: python algorithm data-structures binary-search helper


【解决方案1】:

您的算法存在错误。每当您搜索列表中不存在的数字时,您的算法将继续运行无限循环。

【讨论】:

  • 我必须将“-”切换为“+”低电平。感谢@Ron Zhang 的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多