Signup/Sign In

Linear Search in Python

The linear search operation is the simplest searching operation. In this tutorial, we will perform a linear search operation to discover an element's index position in a list.

Linear Search - A basic Introduction

A method of locating elements in a list is linear search. A sequential search is another name for it. Because it searches for the requested element in a sequential way. It evaluates each and every element in relation to the value we're looking for. The element is discovered if both match and the procedure returns the key's index position.

Let us have a rough understanding of how linear search is performed:

  1. Begin your search with the first element and check the key with each element in the list.
  2. If an element is discovered, the key's index position is returned.
  3. If the element isn't discovered, the return value isn't present.

Algorithm of Linear Search

As of now, we have a rough understanding of linear search operation. Let's have a look at the Algorithm followed by code for better understanding:

  1. Create a function linear_search()
  2. Declare three parameters array, length of the array, and number to be found.
  3. Initialize for loop
  4. Iterate each element and compare the key value.
  5. If the element is present return index
  6. Else return not present

Program of Linear Search

As discussed above in the algorithm let us now dive into the programming part of linear search operation influenced by the algorithm.

def linear_search(arr, a, b):

    # Going through array 
    for i in range(0, a):
        if (arr[i] == b):
            return i
    return -1

arr = [9, 7, 5, 3, 1]
print("The array given is ", arr)
b = 5
print("Element to be found is ", b)
a = len(arr)
index = linear_search(arr, a, b)
if(index == -1):
    print("Element is not in the list")
else:
    print("Index of the element is: ", index)


The array given is [9, 7, 5, 3, 1]
Element to be found is 5
Index of the element is: 2

Conclusion

In this tutorial, we have performed a linear search operation in python programming with the help of a sequential search.



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.