I have tried to implement a binary search algorithm by myself in python and it worked but when I looked into the internet most of them did differently. I don't know which one is better from these two
My Binary Search Algorithm
def binary_search(arr, item):
minVal = 0
maxVal = len(arr) - 1
backtrack = 0
while (True):
midPosition = (maxVal - minVal)//2 + backtrack
mid = arr[midPosition]
if mid > item:
maxVal = midPosition
backtrack = midPosition
elif mid < item:
minVal = midPosition
backtrack = midPosition
else:
print(midPosition)
break
Tutorial's binary search algorithm
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
# If x is greater, ignore left half
if arr[mid] < x:
low = mid + 1
# If x is smaller, ignore right half
elif arr[mid] > x:
high = mid - 1
# means x is present at mid
else:
return mid
# If we reach here, then the element was not present
return -1