diff --git a/01_introduction_to_algorithms/ruby/01_binary_search.rb b/01_introduction_to_algorithms/ruby/01_binary_search.rb new file mode 100644 index 0000000..33762ad --- /dev/null +++ b/01_introduction_to_algorithms/ruby/01_binary_search.rb @@ -0,0 +1,26 @@ +def binary_search(list, item) + low = 0 + high = list.length - 1 + + while low <= high + mid = (low + high) / 2 + guess = list[mid] + + if guess == item + return mid + elsif guess > item + high = mid - 1 + else + low = mid + 1 + end + end + + return nil +end + +my_list = [1, 3, 5, 7, 9] +puts binary_search(my_list, 3) # => 1 + +# We need to use .inspect here because just printing nil +# would output an empty string +puts binary_search(my_list, -1).inspect # => nil