Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Binary Search
- from random import randint
- sorted_list = [randint(0, 100) for i in range(50)] # random to start with
- sorted_list.sort()
- print(sorted_list)
- left, right = 0, len(sorted_list)-1
- def binary_search(sorted_list, left, right, value):
- print(f"left={left}, right={right}")
- if left > right:
- return False
- mid = int((left + right) / 2)
- if sorted_list[mid] > value:
- return binary_search(sorted_list, left, mid - 1, value)
- elif sorted_list[mid] < value:
- return binary_search(sorted_list, mid + 1, right, value)
- else:
- return mid
- value = int(input("What shall we search for?"))
- result = binary_search(sorted_list, left, right, value)
- if result:
- print(f"Value {sorted_list[result]} found at position {result}")
- else:
- print(f"Value {value} not found")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement