Skip to content

Instantly share code, notes, and snippets.

@itstommymorgan
Created March 4, 2010 21:02
Show Gist options
  • Select an option

  • Save itstommymorgan/322105 to your computer and use it in GitHub Desktop.

Select an option

Save itstommymorgan/322105 to your computer and use it in GitHub Desktop.
def chop(search_for, sorted_list)
if sorted_list[0] == search_for
return 0
elsif sorted_list.size == 1 || sorted_list.empty?
return -1
elsif sorted_list[0] > search_for
return -1
else
halfway = sorted_list.size / 2
first_half = sorted_list[0,halfway]
second_half = sorted_list[halfway,halfway + 1]
if second_half[0] > search_for
return chop(search_for, first_half)
else
return chop(search_for, second_half)
end
end
end
Loaded suite test_chop
Started
.
Finished in 0.002076 seconds.
1 tests, 19 assertions, 0 failures, 0 errors
require 'chop'
require 'test/unit'
class TestChop < Test::Unit::TestCase
def test_chop
assert_equal(-1, chop(3, []))
assert_equal(-1, chop(3, [1]))
assert_equal(0, chop(1, [1]))
#
assert_equal(0, chop(1, [1, 3, 5]))
assert_equal(1, chop(3, [1, 3, 5]))
assert_equal(2, chop(5, [1, 3, 5]))
assert_equal(-1, chop(0, [1, 3, 5]))
assert_equal(-1, chop(2, [1, 3, 5]))
assert_equal(-1, chop(4, [1, 3, 5]))
assert_equal(-1, chop(6, [1, 3, 5]))
#
assert_equal(0, chop(1, [1, 3, 5, 7]))
assert_equal(1, chop(3, [1, 3, 5, 7]))
assert_equal(2, chop(5, [1, 3, 5, 7]))
assert_equal(3, chop(7, [1, 3, 5, 7]))
assert_equal(-1, chop(0, [1, 3, 5, 7]))
assert_equal(-1, chop(2, [1, 3, 5, 7]))
assert_equal(-1, chop(4, [1, 3, 5, 7]))
assert_equal(-1, chop(6, [1, 3, 5, 7]))
assert_equal(-1, chop(8, [1, 3, 5, 7]))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment