Tom_Jung

Untitled

Feb 7th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.61 KB | None | 0 0
  1. from random import randint
  2. sorted_list =[randint(0,100) for i in range(1,21)]
  3. sorted_list = sorted(sorted_list)
  4. sorted_list =[2, 5, 12, 12, 12, 35, 36, 47, 53, 54, 57, 66, 69, 72, 75, 78, 86, 86, 97, 98]
  5.  
  6. def binary_search(sorted_list, value):
  7.  
  8. left = 0
  9. right = len(sorted_list) - 1
  10. while left <= right:
  11. mid = int((right + left)/2)
  12. if sorted_list[mid] > value:
  13. right = mid - 1
  14. elif sorted_list[mid] < value:
  15. left = mid + 1
  16. else:
  17. return mid
  18. return False
  19. print("Value is at position", binary_search(sorted_list, 12))
Advertisement
Add Comment
Please, Sign In to add comment