Binary Search code keeps giving Out of Range error

Viewed 48

For binary search, I keep running into an error that the index in my code: "mid", keep being out of range. Is there any way to fix this? Code:

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))
2 Answers

your conditions are messed up see

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))

*inside elif

Issues in your code:

  • You are changing only low in your code everytime. high remains unchanged.
  • When num[mid] > key then the key lies to the left of mid. So high = mid - 1.

This should be the correct implementation.

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))
Related