Created
April 1, 2023 23:19
-
-
Save jainal09/e4bc4876f9d54213ba29c2b376f4b8ad to your computer and use it in GitHub Desktop.
Binary Search in Python
This file contains hidden or 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(nums, target): | |
start = 0 | |
end = len(nums)-1 | |
while start <= end: | |
mid = start + (end-start)//2 | |
if nums[mid] > target: | |
end = mid-1 | |
elif nums[mid] < target: | |
start = mid+1 | |
else: | |
return mid | |
return -1 | |
if __name__ == '__main__': | |
nums = [2, 12, 15, 17, 27, 29, 45] | |
target = 17 | |
print(binary_search(nums, target)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment