Skip to content

Instantly share code, notes, and snippets.

@Chetan-Goyal
Created December 12, 2019 19:54
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 Chetan-Goyal/37fb7e1807f5db5349bc5592da9d1b5b to your computer and use it in GitHub Desktop.
Save Chetan-Goyal/37fb7e1807f5db5349bc5592da9d1b5b to your computer and use it in GitHub Desktop.
binary_search
def BS(arr, n):
l, u = 0, len(arr)-1
while l <= u:
m = (l+u)//2
if n == arr[m]:
return m
elif n < arr[m]:
u = m-1
else:
l = m+1
return -1
print(BS([1,2,3,4,5,6,7,8,9], 7))
print(BS([1,2,3,4,5,6,7,8,9], 10))
@Chetan-Goyal
Copy link
Author

Chetan-Goyal commented Dec 12, 2019

def BS(list, n):

    a = 0
    b = len(arr)-1
    while a <= b:

        c = (a+b)//2

        if n < arr[c]:
            b = c - 1
        elif n> arr[c]:
            a = c + 1
        else:
            return c
    return -1

print(BS([1,2,3,4,5,6,7,8,9], 7))

print(BS([1,2,3,4,5,6,7,8,9], 10))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment