Advertisement
cartagenae

Binary Search (recursive) 1

Nov 18th, 2018
620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. # define binary_search()
  2. def binary_search(sorted_list, target):
  3. if not sorted_list:
  4. return 'value not found'
  5. mid_idx = len(sorted_list)//2
  6. mid_val = sorted_list[mid_idx]
  7. if mid_val == target:
  8. return mid_idx
  9. if mid_val > target:
  10. left_half = sorted_list[:mid_idx]
  11. return binary_search(left_half, target)
  12. if mid_val < target:
  13. right_half = sorted_list[mid_idx+1:]
  14. result = binary_search(right_half, target)
  15. if result == "value not found":
  16. return result
  17. else:
  18. return result + mid_idx + 1
  19. # For testing:
  20. sorted_values = [13, 14, 15, 16, 17]
  21. print(binary_search(sorted_values, 16))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement