# binary search algorithm not working

asked Sep 11, 2017

I'm trying to implement a binary search and somehow my function doesn't return the value wanted

``````import math
def binarySearch(a, l, r, v):
if l >= r:
return -1
mid = math.floor((l + r)/ 2)

if a[mid] == v:
return mid
elif(v < mid):
binarySearch(a,mid+1,r,v)
else:
binarySearch(a,l,mid-1,v)

a = [1,2,5,8,23,67,345]

print(binarySearch(a,0,6,5));
``````

It keeps returning `-1` Can someone shed a light where I went wrong?

answered Sep 11, 2017

You don't have return in elif statement so your function can return only -1

``````import math
def binarySearch(a, l, r, v):
if l > r:
return -1
mid = math.floor((l + r)/ 2)

if a[mid] == v:
return mid
elif(v < a[mid]):
return binarySearch(a,l,mid-1,v)
else:
return binarySearch(a,mid+1,r,v)
``````
answered Sep 11, 2017 by

Try this:

``````int binarySearch(int arr[], int l, int r, int x)
{
if (r>=l)
{
int mid = l + (r - l)/2;

if (arr[mid] == x)
return mid;

if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);

return binarySearch(arr, mid+1, r, x);
}

return -1;
}
``````