-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathLinearSearch.py
42 lines (31 loc) · 1.19 KB
/
LinearSearch.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
# Python program for the execution of linear search algorithm
# The function will loop over every element and return the index if it matches.
# Otherwise, it will return -1
# Defining the function
def linear_search(array, x):
# looping over every element
for i in range(len(array)):
# Comparing the element
if array[i] == x:
return i
# If not found, any index returning -1
return -1
# Implementing the code
array = [5, 8, 16, 37, 59, 80]
print(f"Array = {array}")
# Case - 1:- Element is present in the list
x = 59
# Calling the function
index = linear_search(array, x)
if index != -1:
print(f"The given element {x} is present at the index", str(index))
else:
print(f"The given element {x} is not present in the array")
# Case - 2:- Element is not present in the array
x = 35
# Calling the function
index = linear_search(array, x)
if index != -1:
print(f"The given element {x} is present at the index", str(index))
else:
print(f"The given element {x} is not present in the array")