Signup/Sign In

Python Program for Linear Search

learn Python Language tutorial

In this tutorial, we will learn what is linear search techniques and how they can be implemented in python programs.

Linear search means we will move on sequentially. Linear search is a sequential searching algorithm where we start from one end and check every element of the list until the desired element is found. It is the simplest searching algorithm. It doesn't need the array to be sorted for its implementation

As the output, we are required to get the index number of the element if it is present in the array otherwise -1 if not present.

Look at the given example to understand the working with input and output. Consider the element to be searched is "x".

Input:

array: 3 5 1 2 6

x: 2

Output: 3

Input:

array: 56 9 11 7 60

x: 44

Output: -1

What is Linear Search Algorithm?

The linear search algorithm is suitable for a smaller list (<100) because it checks every element to get the desired number. Suppose there are 10,000 element lists and desired element is available at the last position, this will consume much time by comparing with each element of the list.

Following are the steps of implementation that we will be following:

  1. Traverse the array using a for loop.
  2. In every iteration, compare the target value with the current value of the array.
    • If the values match, return the current index of the array.
    • If the values do not match, move on to the next array element.
  3. If no match is found, return -1.

Linear Search Algorithm

Step 1: Start from the first element, compare the value of "x" with each element of the array one by one.

Step 2: Now if x == value of any element , simply return its index value.

Step 3: Repeat step 2 for every element in the array, if then also this condition comes out to be false, then return -1. This means the element that we are searching for is not present in the given array.

Python Program for Linear Search

# Linear Search in Python


def linearSearch(array, n, x):

    # Going through array sequencially
    for i in range(0, n):
        if (array[i] == x):
            return i
    return -1


array = [2, 4, 0, 1, 9]
x = 1
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
    print("Element not found")
else:
    print("Element found at index: ", result)


An element found at index: 3

Conclusion

In this tutorial, we have seen the simplest searching techniques i.e. linear search using iterative and recursive approaches.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.