Skip to content

Commit d853fa5

Browse files
committed
1 parent 9f64574 commit d853fa5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

binary_search.rb

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# https://codility.com/media/train/12-BinarySearch.pdf
2+
3+
def binary_search(a, x)
4+
n = a.size
5+
back = 0
6+
front = n - 1
7+
result = -1
8+
9+
while back <= front
10+
middle = (back + front) / 2
11+
if a[middle] <= x
12+
back = middle + 1
13+
result = middle if a[middle] == x
14+
else
15+
front = middle - 1
16+
end
17+
end
18+
result
19+
end
20+
21+
require 'minitest/autorun'
22+
23+
class Tests < MiniTest::Unit::TestCase
24+
def test_example_input
25+
assert_equal 5, binary_search([12, 15, 15, 19, 24, 31, 53, 59, 60], 31)
26+
end
27+
28+
def test_not_found
29+
assert_equal -1, binary_search([10, 20, 30], 15)
30+
end
31+
end

0 commit comments

Comments
 (0)