-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search.py
39 lines (30 loc) · 911 Bytes
/
binary_search.py
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
# import pdb
def test(answer):
if( answer == 8 ):
return "Correct"
else:
return( 'Result: %s' %answer )
def binary_search(array, x):
max = len(array) - 1
min = 0
answer = ""
while( answer == "" ):
middle_index = int(round( min + ( (max - min)/2 ) ) )
if(x == array[middle_index]):
answer = middle_index
elif(max - min == 1):
if(array[max] != x and array[min] != x):
answer = "x does not exist in the array"
else:
middle_index = max
answer = middle_index
elif( array[middle_index] < x ):
min = middle_index
elif( array[middle_index] > x ):
max = middle_index
return answer
x = 50
array = [2, 4, 6, 8, 12, 19, 20, 30, 50, 93, 100, 200]
answer = binary_search(array, x)
print(test(answer))
# total RunTime: 0.059