Linear Search
Linear Search
Linear Search
Objective:
To practice the use of linear search on a list in Python without employing functions.
In this program, you'll:
Understand how to handle arrays (lists) in Python: Learn how to initialize, populate,
and manipulate a list.
Implement a linear search algorithm: Find the index of a specific element by checking
each item in the list sequentially.
Handle user input and output: Collect user inputs for array elements and the search
value, and display the results based on the search operation.
Outcomes:
At the end of this exercise, the student will be able to:
Implement Linear Search on a List: Understand and apply the linear search algorithm to
find the index of a specified element in a list.
Handle List Operations in Python: Gain experience in initializing, populating, and
manipulating lists based on user input.
Perform Basic Input and Output Operations: Collect and process user inputs for array
elements and search queries, and display results effectively.
Aim:
Write a Python program to input an array and find an element using linear search without using
functions. Additionally, analyze the time complexity and space complexity of your
implementation.
Theory:
To perform a linear search in an array, check each element sequentially until the target element is
found or the end of the array is reached. The array does not need to be sorted for this method to
work.
If no match is found, print a message indicating that the element is not in the array.
End
Source Code :
Method 1: Linear Searching without using Functions:
'''Write a program in Python to input an array and find an element in it using
Linear Search without using Functions.'''
# Linear Search
count=0
for i in range(n):
if arr[i]==value:
count+=1
break
Output :
# Linear Search in Function with the help of array, size, and target value
def LinearSearch(arr,n,value):
for i in range (n):
if arr[i]==value:
return i
return -1
# If the element was found, return value is the index of the target value, else -1
if LS==-1:
print("Element cannot be found in the Array")
else:
print(f"The Element {value} can be found at the Index Number {LS}")
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology
Output :
Enter the number of elements you want in your Array: 4
Enter Element 1: 10
Enter Element 2: 7
Enter Element 3: 3
Enter Element 4: 6
10,7,3,6
Enter the element you want to find in your array:6
The Element 6 can be found at the Index Number 3
Conclusion:
Thus, we implemented Linear Searching in Python