Created
August 15, 2014 08:30
-
-
Save iaintshine/de87b2209bb1443cb81c to your computer and use it in GitHub Desktop.
A Ruby implementation of a Binary Search Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit' | |
module Search | |
extend self | |
def binary(container, item) | |
_binary container, item, 0, container.length | |
end | |
def _binary(container, item, min, max) | |
return nil if container.empty? | |
mid = midpoint min, max | |
if container[mid] > item | |
return _binary(container, item, min, mid - 1) | |
elsif container[mid] < item | |
return _binary(container, item, mid + 1, max) | |
else | |
return mid | |
end | |
end | |
def midpoint(min, max) | |
min + ((max - min) / 2) | |
end | |
end | |
if __FILE__ == $0 | |
class TestBinarysearch < Test::Unit::TestCase | |
def test_bsearch | |
elements = [1, 3, 4, 6, 8, 9, 11] | |
assert_equal 2, Search.binary(elements, 4) | |
assert_equal 5, Search.binary(elements, 9) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment