Skip to content

Instantly share code, notes, and snippets.

@jainal09
Created April 1, 2023 23:19
Show Gist options
  • Save jainal09/e4bc4876f9d54213ba29c2b376f4b8ad to your computer and use it in GitHub Desktop.
Save jainal09/e4bc4876f9d54213ba29c2b376f4b8ad to your computer and use it in GitHub Desktop.
Binary Search in Python
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