- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.py
More file actions
Latest commit
48 lines (37 loc) · 1.13 KB
/
Copy pathbinarySearch.py
File metadata and controls
48 lines (37 loc) · 1.13 KB
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
importrandom
importtime
defnaive_search(l, target):
foriinrange(len(l)):
ifl[i] ==target:
returni
return-1
defbinary_search(l, target, low=None, high=None):
iflowisNone:
low=0
ifhighisNone:
high=len(l) -1
ifhigh<low:
return-1
midpoint= (low+high) //2# 2
ifl[midpoint] ==target:
returnmidpoint
eliftarget<l[midpoint]:
returnbinary_search(l, target, low, midpoint-1)
else:
returnbinary_search(l, target, midpoint+1, high)
if__name__=='__main__':
length=10000
sorted_list=set()
whilelen(sorted_list) <length:
sorted_list.add(random.randint(-3*length, 3*length))
sorted_list=sorted(list(sorted_list))
start=time.time()
fortargetinsorted_list:
naive_search(sorted_list, target)
end=time.time()
print("Naive search time: ", (end-start), "seconds")
start=time.time()
fortargetinsorted_list:
binary_search(sorted_list, target)
end=time.time()
print("Binary search time: ", (end-start), "seconds")