Computer Science Related Others Courses AvailableThe Best Codder.blogspot.com

write a program to implement linear and binary search on list in p;ython

write a program to implement linear and binary search on list in p;ython
1 min read

 

Linear Search in Python

Python is one of the most popular and powerful languages. It takes a few lines to execute the code, which makes it much user-friendly language. In this tutorial, we will learn the linear search in Python. Searching is a technique to find the particular element is present or not in the given list.

There are two types of searching -

Python Program

Let's understand the following Python implementation of the linear search algorithm.

Program

  1. def linear_Search(list1, n, key):  
  2.   
  3.     # Searching list1 sequentially  
  4.     for i in range(0, n):  
  5.         if (list1[i] == key):  
  6.             return i  
  7.     return -1  
  8.   
  9.   
  10. list1 = [1 ,3, 5, 4, 7, 9]  
  11. key = 7  
  12.   
  13. n = len(list1)  
  14. res = linear_Search(list1, n, key)  
  15. if(res == -1):  
  16.     print("Element not found")  
  17. else:  
  18.     print("Element found at index: ", res)  

Output:

Element found at index:  4

Explanation:

In the above code, we have created a function linear_Search(), which takes three arguments - list1, length of the list, and number to search. We defined for loop and iterate each element and compare to the key value. If element is found, return the index else return -1 which means element is not present in the list

What is a Linear Search?

Linear search is a method of finding elements within a list. It is also called a sequential search.  It is the simplest searching algorithm because it searches the desired element in a sequential manner.

Let's understand the following steps to find the element key = 7 in the given list.

Step - 1: Start the search from the first element and Check key = 7 with each element of list x.

Linear Search in Python

Step - 2: If element is found, return the index position of the key.

Linear Search in Python

Step - 3: If element is not found, return element is not present.

Linear Search in Python

Linear Search Algorithm

There is list of n elements and key value to be searched.

Below is the linear search algorithm.

  1. LinearSearch(list, key)  
  2.   for each item in the list  
  3.     if item == value  
  4.       return its index position  
  5.    return -1  

Post a Comment

© 2025Python . The Best Codder All rights reserved. Distributed by