-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search.py
53 lines (43 loc) · 1011 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import random
def binary_search(arr, target, start = 0, end = None):
if end == None: end = len(arr)-1
mid = (start + end) // 2
if start >= end and arr[mid] != target:
#Not found return None
return None
if(arr[mid] < target):
start = mid + 1
elif (arr[mid] > target):
end = mid - 1
else:
return mid
return binary_search(arr, target, start, end)
def binary_search_iterative(arr, target):
end = len(arr) -1
start = 0
while(start <= end):
mid = (start + end) //2
if arr[mid] < target:
start = mid + 1
elif arr[mid] > target:
end = mid - 1
else:
return mid
if start <= end and arr[mid] != target:
return None
def main():
r = []
a = range(-109,120)
r[:] = a + [-121,222]
#print(binary_search(a,119))
random.shuffle(r)
for t in r:
try:
if a[binary_search_iterative(a,t)] != t:
print("Failed!")
print("target {}".format(t))
#print("found {}".format(a[binary_search(a,t)]))
except Exception, e:
print(e)
if __name__ == '__main__':
main()