require "test/unit"
# Iterative implementation
def chop ( target, values)
start = 0
stop = values.length # stop indexes one past the end of the array
# loop until something is found or until we
# run out of elements to search
while start != stop
# Find the middle
mid = start + ( stop - start) / 2
# Check to see if we got lucky
return mid if values[ mid] == target
# Not this time ... so lets see which half it might be in
if target < values[ pos]
stop = mid
else
start = mid + 1
end
end
# Didn't find what we were looking for
return - 1
end
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
#puts test_chop
cmVxdWlyZSAidGVzdC91bml0IgoKIyBJdGVyYXRpdmUgaW1wbGVtZW50YXRpb24KZGVmIGNob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