I wrote the binary search algorithm with Ruby, the code is below. The question is if there's any way to make it look cleaner?
def binary_search(sample_array, x, l, r)
mid = (l + r)/2
return -1 if r < l
return binary_search(sample_array, x, l, mid-1) if (sample_array[mid] > x)
return binary_search(sample_array, x, mid+1, r) if (sample_array[mid] < x)
return mid if (sample_array[mid] == x)
end
result = binary_search(sample_array, x, l, r)
puts "#{result}"
It seems to me that returns can be minimised or even some more Ruby idioms added. Tried to use lambda, but smth went wrong.
l
orr
(or returning) according to the comparisons betweensample_array[mid]
andx
. \$\endgroup\$