'Binary search recursive function not working if target is either the first, or last element in the array

I've been working on this recursive function in Ruby for quite some time now. There's one problem, which I can't seem to fix on my own.

def bsearch(array, target)
    pos = (array.length - 1) / 2
    return pos if array[pos] == target
    if array[pos] < target
        pos += bsearch(array[pos..-1], target)
    else
        pos -= bsearch(array[0..pos], target)
    end
end

The code seems to work as long as the target isn't the first or last element in the array. I can't find the solution to this problem.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source