I'm reading the Grokking Algorithms book, and I'm implementing the binary_search function but recursively, so, my algorithm works if the item is in the list.
Any suggestions on how to control when I have a nil?
def recursive_binary_search(list, item)
if list.length == 0
return nil
elsif list.length == 1
print list
if list.first == item
return 0
else
return nil
end
else
low = 0
high = list.length - 1
mid = (low + Float(high - low)/2).round()
guess = list[mid]
if guess == item
return mid
elsif guess < item
return mid + 1 + recursive_binary_search(list[mid+1..-1], item)
else
return recursive_binary_search(list[0..mid-1], item)
end
end
end
my_list = [1, 3, 5, 7, 9]
puts recursive_binary_search(my_list, 100) # => nil
return nilis the same asreturn.