Linear Search in Python

Harshit Jindal Jan 03, 2023 Feb 24, 2021 Python Python Algorithm
  1. Linear Search Algorithm
  2. Linear Search Python Implementation
Linear Search in Python
If you want to understand Linear Search in detail then refer to the Linear Search Algorithm article.

Linear Search Algorithm

Let us assume that we have an unsorted array A[] containing n elements, and we want to find an element - X.

  • Traverse all elements inside the array starting from the leftmost element using a for loop and do the following:
    • If the value of A[i] matches with X, then return the index i. (If there can be multiple elements matching X, then instead of returning the index i, either print all indexes or store all the indexes in an array and return that array.)
    • Else move on to the next element.
    • If it is at the last element of the array, quit the for loop.
  • If none of the elements matched, then return -1.

Linear Search Python Implementation

def linearsearch(arr, n, x):
    for i in range(0, n):
        if (arr[i] == x):
            return i
    return -1

arr = [1, 2, 3, 4, 5]
x = 1
n = len(arr)
position = linearsearch(arr, n, x)
if(position == -1):
    print("Element not found !!!")
    print("Element is present at index", position)


Element is found at index: 1

The time complexity of the above algorithm is O(n).

Related Article - Python Algorithm

  • Smith-Waterman Algorithm in Python
  • Rabin-Karp Algorithm in Python
  • Union-Find Algorithm in Python
  • Depth-First Search in Python
  • Sieve of Eratosthenes in Python