Doing it recursively is a simple re-write. The while changes to an if and the asignments of hi and lo turn into recursive calls. In a language with tail call removal, this would not be any worse than the iterative version. I don't think Ruby is one of those languages. However, I do think this version is a bit easier to read than the first one.
module BinChopper
def chop(n, a)
return recursive_chop(n, a, a.length - 1, 0)
end
def recursive_chop(n, a, hi, lo)
if lo > hi
return -1
end
mid = (lo + hi) / 2
if a[mid] == n
return mid
elsif (a[mid] > n)
return recursive_chop(n, a, mid - 1, lo)
else
# a[mid] must be less than n
return recursive_chop(n, a, hi, mid + 1)
end
end
end