-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCMPE365 Lab 3 Search Algorithms.py
68 lines (51 loc) · 1.21 KB
/
CMPE365 Lab 3 Search Algorithms.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
# coding: utf-8
# Search algorithms.
# @author Stefan Robb
# In[46]:
def Bin_Search(A,x):
first = 0
last = len(A) - 1
count = 1
while(first <= last):
mid = int((first + last)/2)
if A[mid] == x:
return count
elif A[mid] > x:
last = mid - 1
else:
first = mid + 1
count = count + 1
return -1
# In[53]:
def Trin_Search(A,x):
first = 0
last = len(A) - 1
count = 1
while first <= last:
t1 = int(first + (last - first)/3)
if A[t1] == x:
return t1
elif A[t1] > x: # reduce to the first third
last = t1 - 1
else:
first = t1 + 1
if first > last:
return -1
mid = int((first + last)/2)
if A[mid] == x:
return count
elif A[mid] > x: # reduce to the middle third
last = mid - 1
else:
first = mid + 1 # reduce to the last third
count = count + 1
return -1
# In[95]:
A = []
size = 4000
for i in range(0,size):
A.append(i)
x = 876
print(Bin_Search(A,x))
print(Trin_Search(A,x))