Advertisement
cartagenae

Binary Search (iterative)

Nov 18th, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. def binary_search(sorted_list, target):
  2. left_pointer = 0
  3. right_pointer = len(sorted_list)
  4.  
  5. # fill in the condition for the while loop
  6. while left_pointer < right_pointer:
  7. # calculate the middle index using the two pointers
  8. mid_idx = (left_pointer + right_pointer) // 2
  9. mid_val = sorted_list[mid_idx]
  10. if mid_val == target:
  11. return mid_idx
  12. if target < mid_val:
  13. # set the right_pointer to the appropriate value
  14. right_pointer = mid_idx
  15. if target > mid_val:
  16. # set the left_pointer to the appropriate value
  17. left_pointer = mid_idx + 1
  18.  
  19. return "Value not in list"
  20.  
  21. # test cases
  22. print(binary_search([5,6,7,8,9], 9))
  23. print(binary_search([5,6,7,8,9], 10))
  24. print(binary_search([5,6,7,8,9], 8))
  25. print(binary_search([5,6,7,8,9], 4))
  26. print(binary_search([5,6,7,8,9], 6))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement