Created
July 7, 2020 04:49
-
-
Save kafagy/8dd85a611310878c923cf1a833285d95 to your computer and use it in GitHub Desktop.
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(arr, x): | |
low = 0 | |
high = len(arr) - 1 | |
mid = 0 | |
while low <= high: | |
mid = (high + low) // 2 | |
# Check if x is present at mid | |
if arr[mid] < x: | |
low = mid + 1 | |
# If x is greater, ignore left half | |
elif arr[mid] > x: | |
high = mid - 1 | |
# If x is smaller, ignore right half | |
else: | |
return mid | |
# If we reach here, then the element was not present | |
return -1 | |
# Test array | |
arr = [ 2, 3, 4, 10, 40 ] | |
x = 10 | |
# Function call | |
result = binary_search(arr, x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment