Skip to content

Instantly share code, notes, and snippets.

@shivankgtm
Last active October 2, 2019 21:24
Show Gist options
  • Save shivankgtm/2a5c9cf297d34faa46ee43a053317cb5 to your computer and use it in GitHub Desktop.
Save shivankgtm/2a5c9cf297d34faa46ee43a053317cb5 to your computer and use it in GitHub Desktop.
array = [1,3,6,10,15,32,43,46,100,150,170,290] # Given
def BinarySearch(array, target):
n = len(array) # length of array.
left = 0 # at starting are search space is
right = n-1 # full array(from index 0 to n-1)
# Now remember what we talk about condition for search.
# If are left and right index are same or they are at same positon
# It is time to stop.
# which also means that are left index should not cross right index.
while left <= right:
mid = (left + right)//2 # middle point we talked about
if array[mid] == target:
return mid # returning the index vaue
elif array[mid] < target:
left = mid+1 # now your search space is halfed.
else:
right = mid-1 # now your search space is halfed
return 'Element does not exist.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment