Python Program for Linear Search

Before going to the program first let us understand what is a Linear Search?

Linear search:

          Linear search is the simplest search algorithm. It is also called a sequential search.

Linear search is a method for finding a particular value in a list that checks each element in sequence until the desired element is found or the list is exhausted.

For Linear search, the list need not be ordered.

Related: Python program for binary search

Program code for Linear Search in Python:

# Python Program for Linear Search
# Initialize an empty list and the flag variable
array = []
element_found = False

size = int(input("Enter the size of an array: "))

# Read the elements from the user
for i in range(size):
    elements = int(input("Enter the Element: "))
    array.append(elements)

# Read the element to be searched from the user 
element = int(input("Enter the element to be searched: "))

for i in range(size):
    if element == array[i]:
        position = i
        element_found = True
        break

if element_found:
    print("The element is in the list and its position is: ", position + 1)
else:
    print("The element is not found")

Output:

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *