Binary Search implementation in Ruby

  1. def binary_search(array, value, from=0, to=nil)
  2.     to = array.count - 1 unless to
  3.     mid = (from + to) / 2
  4.     if value < array[mid]
  5.       return binary_search(array, value, from, mid - 1)
  6.     elsif value > array[mid]
  7.       return binary_search(array, value, mid + 1, to)
  8.     else
  9.       return mid
  10.     end
  11. end

puts binary_search([1,2,3,4,5,7,8,9,10,12,15,16,17,18], 15)

Comments

Popular posts from this blog

Rails Kaminari - Ajax pagination

Rails 4, MySQL, and Emoji (Mysql2::Error: Incorrect string value: '\xF0\x9F\x8C\x9D')