二进制搜索代码不断给出超出范围错误

Binary Search code keeps giving Out of Range error

对于二进制搜索,我将 运行 保存为错误,即我的代码中的索引:“mid”,一直超出范围。有没有什么办法解决这一问题? 代码:

def binary_search(num, key):
  low = 0
  high = len(num)
  while high >= low:
    mid = (low + high)//2
    if num[mid] < key:
      low = mid + 1
    elif num[mid] > key:
      low = mid + 1
    else:
      return mid
  return -1
A = [2, 4, 7, 10, 11, 32, 45, 87, 90]
print(binary_search(A, 10))

你的条件一团糟见

def binary_search(num, key):
  low = 0
  high = len(num)
  while high >= low:
    mid = (low + high)//2
    if num[mid] < key:
      low = mid + 1
    elif num[mid] > key:
      high = mid - 1
    else:
      return mid
  return -1
A = [2, 4, 7, 10, 11, 32, 45, 87, 90]
print(binary_search(A, 10))

*elif 内部

您的代码中的问题:

  • 您每次只更改 low 代码。 high保持不变。
  • num[mid] > key 时,键位于 mid 的左侧。所以 high = mid - 1.

这应该是正确的实现方式。

def binary_search(num, key):
  low = 0
  high = len(num)-1
  while high >= low:
    mid = (low + high)//2
    if num[mid] < key:
      low = mid + 1
    elif num[mid] > key:
      high = mid - 1
    else:
      return mid
  return -1
A = [2, 4, 7, 10, 11, 32, 45, 87, 90]
print(binary_search(A, 11))