-
Notifications
You must be signed in to change notification settings - Fork 0
/
alg_sequential_search.py
61 lines (51 loc) · 1.59 KB
/
alg_sequential_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
54
55
56
57
58
59
60
61
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def sequential_search(a_list, item):
"""Sequential search by iteration."""
pos = 0
is_found = False
while pos < len(a_list) and not is_found:
if a_list[pos] == item:
is_found = True
else:
pos += 1
return is_found
def sequential_search_ordered(a_list, item):
"""Sequential search by ordering first."""
a_list = sorted(a_list)
pos = 0
is_found = False
is_stop = False
while pos < len(a_list) and not is_found and not is_stop:
if a_list[pos] == item:
is_found = True
else:
if a_list[pos] > item:
is_stop = True
else:
pos += 1
return is_found
def main():
import time
a_list = [54, 26, 93, 17,77, 31, 44, 55, 20, 65]
start_time = time.time()
item = 65
print('Search item {0}: {1}'
.format(item, sequential_search(a_list, item)))
item = 100
print('Search item {0}: {1}'
.format(item, sequential_search(a_list, item)))
print('Time for sequential sorts: {}'
.format(time.time() - start_time))
start_time = time.time()
item = 65
print('Search item {0}: {1}'
.format(item, sequential_search_ordered(a_list, item)))
item = 100
print('Search item {0}: {1}'
.format(item, sequential_search_ordered(a_list, item)))
print('Time for sequential sort ordered: {}'
.format(time.time() - start_time))
if __name__ == '__main__':
main()