Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Binary searching for the list
- from random import randint
- def binary_search(sorted_list, value):
- # left to 0
- left = 0
- # right to highest index in list
- right = len(sorted_list) - 1
- # loop that ends when left > right
- while left <= right:
- # mid to int between left and right
- mid = int((right + left)/2)
- # if sorted_list[mid] > value set right to mid
- if sorted_list[mid] > value:
- right = mid - 1
- # if sorted_list[mid] < value set left to mid
- elif sorted_list[mid] < value:
- left = mid + 1
- # if sorted_list[mid] == value return mid
- else:
- return mid
- # loop ends return `False`
- return False
- sorted_list = [7,4,9,12,18,20,35,66]
- value = 12
- binary_search(sorted_list, 10)
- print("list of numbers is {}".format(sorted_list))
- print(binary_search(sorted_list, value))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement