 Sequential Search or linear search program in python - python coding

Published at - Sep 07, 2021

In this lesson on python coding, we will talk about one of the fundamental algorithms in computer science linear search or sequential search with algorithm. Linear Search search algorithm is a very common question for python coding interviews. This article will help if you are preparing for a python coding interview, so let's try to write a simple python program to implement the linear search tree in python.

These are some highlighted points about linear search algorithm
• Search items in sequence.
• Complexity of the sequential search, is O(n).
• Sequential search can be improved by ordering the list in the case when the searched item is absent.

Algorithm

Linear Search ( Array A, Value x)

Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 8: Exit

Method 1 - Linear Serach

def lin_search(search_list,item):
pos = 0
found = False

if search_list[pos] == item:
found = True
pos = pos +1

return found

print lin_search([1,2,3,5,8],6)
print lin_search([1,2,3,5,8],5)

Method 2 - Linear Search

def lin_search(target, array)
counter = 0
results = []

while counter < array.length
if array[counter] == target
results << counter
counter += 1
else
counter += 1
end
end

if results.empty?
return False
else
return True
end
end

print lin_search([1,2,3,5,8],6)
print lin_search([1,2,3,5,8],5)

The above python program will search for your given input in the array and provides the boolean value if the given input is found in the given list or not.

Related Posts -

Binary search program in py ...

In this lesson on python coding, we will talk about one of the most fam...

Bubble sort examples in pyt ...

In this lesson on python coding, we will talk about one of the fundamental ...

Selection sort examples in ...

In this lesson on python coding, we will talk about one of the fundamen...

Quick Sort explained - pyth ...

Quicksort is an in-place sorting algorithm. Developed by British computer s...

Hash table program in pytho ...

In this lesson on python coding, we will talk about one of the most fam...  