Binary Search implementation in Ruby
- def binary_search(array, value, from=0, to=nil)
- to = array.count - 1 unless to
- mid = (from + to) / 2
- if value < array[mid]
- return binary_search(array, value, from, mid - 1)
- elsif value > array[mid]
- return binary_search(array, value, mid + 1, to)
- else
- return mid
- end
- end
puts binary_search([1,2,3,4,5,7,8,9,10,12,15,16,17,18], 15)
Comments
Post a Comment