adsterra

Linear Search Algorithm and Program using Python | Linear search code


Linear Search

  • Linear search is a very simple search algorithm.
  • In this type of search, a sequential search is made over all items one by one.
  • Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.
In this post we will learn basic of the linear search using three steps:
   1. Algorithm
   2.Pseudo Code
   3. Code


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 Ali] = 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 7: Print element not found
Step 8: Exit


2.Pseudo Code


procedure linear_search (list, value)
   for each item in the list
      if match item == value
             return the item's location
       end if
    end for
 end procedure



3.Code

def search (arr, n, x):
    for i in range(0,n):
        if (arr[i] == x):
            return i
    return -1
  #creating array list
arr = [2,3,4,45,60,80]   
x= 60
n = len(arr)
result = search(arr, n ,x)
if result== -1:
    print("Element is not present in Array")
else:
    print("Element is present at index:-",result)   




Output:-


Linear Search output



Post a Comment

0 Comments