Advertisement
Guest User

binary search

a guest
Mar 31st, 2020
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. # Binary Search
  2. from random import randint
  3.  
  4. sorted_list = [randint(0, 100) for i in range(50)] # random to start with
  5. sorted_list.sort()
  6. print(sorted_list)
  7. left, right = 0, len(sorted_list)-1
  8.  
  9. def binary_search(sorted_list, left, right, value):
  10. print(f"left={left}, right={right}")
  11. if left > right:
  12. return False
  13. mid = int((left + right) / 2)
  14. if sorted_list[mid] > value:
  15. return binary_search(sorted_list, left, mid - 1, value)
  16. elif sorted_list[mid] < value:
  17. return binary_search(sorted_list, mid + 1, right, value)
  18. else:
  19. return mid
  20.  
  21. value = int(input("What shall we search for?"))
  22. result = binary_search(sorted_list, left, right, value)
  23. if result:
  24. print(f"Value {sorted_list[result]} found at position {result}")
  25. else:
  26. print(f"Value {value} not found")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement