GodIsGood
GodIsGood

Reputation: 79

binary search algorithm not working

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?

Upvotes: 0

Views: 71

Answers (2)

sarjit07
sarjit07

Reputation: 10559

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;
}

Upvotes: 0

Misho Tek
Misho Tek

Reputation: 644

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)

Upvotes: 2

Related Questions