-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search.rb
40 lines (37 loc) · 880 Bytes
/
binary_search.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def test(answer)
if answer == 8
return "Correct"
else
return "Result: #{answer}"
end
end
def binary_search(array, x)
max = array.length - 1
min = 0
answer = ""
while answer == ""
middle_index = ( min + ((max - min )/ 2).to_i )
if x == array[middle_index]
answer = middle_index
# if the numbers are next to each other
elsif max - min == 1
if array[max] != x && array[min] != x
answer = "x does not exist in the array"
else
#the min is already checked in line 9
middle_index = max
answer = middle_index
end
elsif array[middle_index] < x
min = middle_index
elsif array[middle_index] > x
max = middle_index
end
end
return answer
end
x = 50
array = [2, 4, 6, 8, 12, 19, 20, 30, 50, 93, 100, 200]
# Runtime: 0.03s
answer = binary_search(array, x)
test(answer)