Skip to content

Commit a1a41e9

Browse files
author
Leon Rische
committed
code for chapter 1 in ruby
1 parent 2a01a0f commit a1a41e9

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
def binary_search(list, item)
2+
low = 0
3+
high = list.length - 1
4+
5+
while low <= high
6+
mid = (low + high) / 2
7+
guess = list[mid]
8+
9+
if guess == item
10+
return mid
11+
elsif guess > item
12+
high = mid - 1
13+
else
14+
low = mid + 1
15+
end
16+
end
17+
18+
return nil
19+
end
20+
21+
my_list = [1, 3, 5, 7, 9]
22+
puts binary_search(my_list, 3) # => 1
23+
24+
# We need to use .inspect here because just printing nil
25+
# would output an empty string
26+
puts binary_search(my_list, -1).inspect # => nil

0 commit comments

Comments
 (0)