binary search algorithm not working

0 votes
asked Sep 11, 2017 by godisgood

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?

2 Answers

0 votes
answered Sep 11, 2017 by misho-tek

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)
0 votes
answered Sep 11, 2017 by sarjit07

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;
}
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...