I'm a newbie in algorithms. I have recently started studying binary search and tryed to implement it on my own. The task is simple: we have an array of integers a
and an integer x
. If a
contains x
the result should be its index, otherwise the function should return -1
.
Here is the code I have written:
def binary_search(a, x):
l = 0
r = len(a)
while r - l > 0:
m = (l + r) // 2
if a[m] < x:
l = m
else:
r = m
if a[l] == x:
return l
return -1
But this code stucks in infinite cycle on a = [1, 2]
and x = 2
. I suppose, that I have incorrect cycle condition (probably, should be r - l >= 0
), but this solution does not help. Where am I wrong?