Skip to content

Instantly share code, notes, and snippets.

@AndreVallestero
Created November 2, 2021 01:14
Show Gist options
  • Save AndreVallestero/5b7ccfe85422ed2d0a9259578e7c00f1 to your computer and use it in GitHub Desktop.
Save AndreVallestero/5b7ccfe85422ed2d0a9259578e7c00f1 to your computer and use it in GitHub Desktop.
binary_search.py
def binarySearch(arr, x):
maxIndex = len(arr) - 1
low = 0
high = maxIndex
mid = 0
while low <= high:
mid = (low + high) // 2
if arr[mid] < x: low = mid + 1
elif arr[mid] > x: high = mid - 1
else: return mid
midDiff = abs(x - arr[mid])
if mid > 0:
subDiff = abs(x - arr[mid-1])
if subDiff < midDiff: return mid - 1
if mid < maxIndex:
addDiff = abs(x - arr[mid+1])
if addDiff < midDiff: return mid + 1
return mid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment