Last active
November 1, 2016 18:32
-
-
Save henryaj/ac56b9cdc4db9e1c11382dfd5f21b9eb to your computer and use it in GitHub Desktop.
Binary search in Ruby
This file contains 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
def binary_search(array, target) | |
return false if array.length == 0 | |
if array.length == 1 | |
return true if array.first == target | |
return false | |
end | |
midpoint = array.length / 2 | |
lower = array[0..midpoint-1] | |
middle = array[midpoint] | |
upper = array[midpoint+1..-1] | |
if target == middle | |
return true | |
elsif target < middle | |
binary_search(lower, target) | |
elsif target > middle | |
binary_search(upper, target) | |
end | |
end | |
require "minitest/autorun" | |
class TestBinarySearch < Minitest::Test | |
def setup | |
@sorted_array1 = [1,2,3,4,7,8,12,15,17,22,23,35,37,45,46,67,69,99,100] | |
@sorted_array2 = [1,2,3,4,7,8,12,15,17,22,23,35,37,45,46,67,69,99] | |
end | |
def test_works_on_odd_numbered_array | |
assert_equal binary_search(@sorted_array1, 3), true | |
assert_equal binary_search(@sorted_array1, 5), false | |
assert_equal binary_search(@sorted_array1, 12), true | |
assert_equal binary_search(@sorted_array1, 69), true | |
assert_equal binary_search(@sorted_array1, 70), false | |
end | |
def test_works_on_even_numbered_array | |
assert_equal binary_search(@sorted_array2, 3), true | |
assert_equal binary_search(@sorted_array2, 5), false | |
assert_equal binary_search(@sorted_array2, 12), true | |
assert_equal binary_search(@sorted_array2, 69), true | |
assert_equal binary_search(@sorted_array2, 70), false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment