Here is my code:
Try to search a element from the list using age old binary search algo,
def binary_search(l, low, high, val):
while low <= high:
mid = (high + low) // 2
#print(mid)
if l[mid] > val:
high = mid - 1
elif l[mid] < val:
low = mid + 1
else:
return mid
return -1
arr = [1,24,5,3]
result = binary_search(arr, 0,(len(arr)-1), 5)
if result == -1:
print(" Not present")
else:
print("given number present at index", result)
Output is: "Not present"
I am not able to get the issue where exactly it is missing to get the correct index, why is it not retuning the index = 2 for the given arr. Please help.
In Binary search array should be sorted.
Try with arr = [1,3,5,24]