ruby - Why is my version of bsearch not working? -
i running bsearch([1,2,3,4,5,6], 6)
this version of bsearch:
def bsearch(arr, target) return nil if arr.size == 0 half = arr.size / 2 left = arr[0...half] right = arr[half...-1] case target <=> arr[half] when 1 return half + bsearch(right, target) when 0 return half when -1 return bsearch(left, target) end end
this error being thrown:
recursion.rb:224:in `+': nil can't coerced fixnum (typeerror) recursion.rb:224:in `bsearch' recursion.rb:224:in `bsearch' recursion.rb:249:in `<main>'
from ruby docs:
.. run beginning end inclusively. created using ... exclude end value
your code excluding final array element.
left = arr[0...half] right = arr[half...-1]
change use range operator ..
instead of ...
left = arr[0..half] right = arr[half..-1]
Comments
Post a Comment