-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlinear_search.py
61 lines (47 loc) · 1.54 KB
/
linear_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 random import randint
"""
Python code for linearly search x in arr[]. If x
is present then return its location, otherwise
return None.
"""
def iterative(array, element):
"""
Perform Linear Search by Iterative Method.
:param array: Iterable of elements.
:param element: element to be searched.
:return: returns value of index of element (if found) else return None.
"""
for i in range(len(array)):
if array[i] == element:
return i
return None
def recursive(array, element, low):
"""
Perform Linear Search by Recursive Method.
:param array: Iterable of elements.
:param low: traversing variable of an array.
:param element: element to be searched.
:return: returns value of index of element (if found) else return None.
"""
if array[low]==element:
return low
if low==len(array)-1:
return None
return recursive(array, element, low+1)
def main():
array = [randint(1,100) for _ in range(100)]
element = randint(1,100)
print(array)
print(element)
result = recursive(array, element, 0)
if result is None:
print('Recursive Linear Search : Element not present in array')
else:
print('Recursive Linear Search : Element is present at index', result)
result = iterative(array, element)
if result is None:
print('Iterative Linear Search : Element not present in array')
else:
print('Iterative Linear Search : Element is present at index', result)
if __name__ == '__main__':
main()