Created
December 9, 2023 22:40
-
-
Save lgliducik/776002212f9ce2a7f073268b33011f6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def binary_search(sequence, find_elem): | |
end_element = len(sequence) - 1 | |
start_element = 0 | |
while start_element <= end_element: | |
middle_element = start_element + (end_element - start_element) // 2 | |
if sequence[middle_element] == find_elem: | |
return middle_element | |
elif sequence[middle_element] < find_elem: | |
start_element = middle_element + 1 | |
else: | |
end_element = middle_element - 1 | |
return -1 | |
list1 = [12, 24, 32, 39, 45, 50, 54] | |
n = 45 | |
result = binary_search(list1, n) | |
if result != -1: | |
print("Element is present at index", str(result)) | |
else: | |
print("Element is not present in list1") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment