Created
November 2, 2021 01:14
-
-
Save AndreVallestero/5b7ccfe85422ed2d0a9259578e7c00f1 to your computer and use it in GitHub Desktop.
binary_search.py
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 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