Skip to content

Instantly share code, notes, and snippets.

@Edald123
Created July 20, 2021 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Edald123/722117fadabd600ba2772e79a5d1e854 to your computer and use it in GitHub Desktop.
Save Edald123/722117fadabd600ba2772e79a5d1e854 to your computer and use it in GitHub Desktop.
Binary search in Python
def binary_search(sorted_list, target):
left_pointer = 0
right_pointer = len(sorted_list)
while left_pointer < right_pointer:
# calculate the middle index using the two pointers
mid_idx = (left_pointer + right_pointer) // 2
mid_val = sorted_list[mid_idx]
if mid_val == target:
return mid_idx
if target < mid_val:
# set the right_pointer to the appropriate value
right_pointer = mid_idx
if target > mid_val:
# set the left_pointer to the appropriate value
left_pointer = mid_idx + 1
return "Value not in list"
# test cases
print(binary_search([5, 6, 7, 8, 9], 9))
print(binary_search([5, 6, 7, 8, 9], 10))
print(binary_search([5, 6, 7, 8, 9], 8))
print(binary_search([5, 6, 7, 8, 9], 4))
print(binary_search([5, 6, 7, 8, 9], 6))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment