scipiguy

Programming 102: Binary search

Jul 5th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1. number_list = [3, 8, 7, 9, 2, 1, 4]
  2. number_list.sort()
  3. print(number_list)
  4.  
  5. def binary_search(number_list, key):
  6.     left = 0
  7.     right = len(number_list)-1
  8.  
  9.     while left <= right:
  10.         print (left, right)
  11.         mid = int((right + left) / 2)
  12.         print(mid)
  13.         if number_list[mid] > key:
  14.             right = mid - 1
  15.         elif number_list[mid] < key:
  16.             left = mid + 1
  17.         else:
  18.             return mid
  19.     return False
  20.            
  21. key = int(input("What number are you looking for? "))
  22. response = binary_search(number_list, key)
  23.  
  24. if response == False:
  25.     print("Your value was not found!")
  26. else:
  27.     print("Your value was found!")
Advertisement
Add Comment
Please, Sign In to add comment