Skip to content

Instantly share code, notes, and snippets.

@rreinhardt9
Created December 27, 2017 16:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rreinhardt9/1688261e5db5c4ebb02749151d6c37d5 to your computer and use it in GitHub Desktop.
Save rreinhardt9/1688261e5db5c4ebb02749151d6c37d5 to your computer and use it in GitHub Desktop.
A Binary Search Implementation
class Bsearch
def initialize(dictionary)
@dictionary = Array(dictionary)
end
def search(value)
search_in_chunk(@dictionary, value)
end
private
def search_in_chunk(chunk, value)
return (chunk[0] == value ? 0 : raise("Not Found")) if chunk.one?
middle_index = middle_index(chunk)
middle_value = chunk.at(middle_index)
if middle_value == value
return middle_index
elsif middle_value > value
return search_in_chunk(chunk[0...middle_index], value)
elsif middle_value < value
return (search_in_chunk(chunk[(middle_index)..-1], value) + middle_index)
end
end
def middle_index(dict)
dict.size / 2
end
end
require 'minitest/autorun'
require_relative 'bsearch'
class TestBsearch < Minitest::Test
def setup
@bsearch = Bsearch.new([1,2,3,5,8,13])
end
def test_returns_value_in_array_to_right
assert_equal 4, Bsearch.new([1,2,3,5,8,13]).search(8)
end
def test_returns_value_in_array_to_left
assert_equal 0, Bsearch.new([1,2,3,5,8,13]).search(1)
end
def test_returns_raise_error_if_not_in_dictionary
err = assert_raises(RuntimeError) { @bsearch.search(42) }
assert_equal "Not Found", err.message
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment