The Wayback Machine - https://web.archive.org/web/20241218111715/https://www.geeksforgeeks.org/python-program-for-linear-search/
Open In App

Python Program for Linear Search

Last Updated : 23 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[] using Python. 

Examples:

Input: arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']          
# Element to Find
x = 'J'
Output : 9

Explanation: A simple approach is to do a linear search, i.e

  • Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
  • If x matches with an element, return the index.
  • If x doesn’t match with any of the elements, return -1.

Python Program for Linear Search Iterative Approach

This takes an array arr and a target element to search. Iterates through each element of the array and compares it with the target. If a match is found, it returns the index of the element. If the target is found, it returns its index; otherwise, it returns -1.

Python
# Python program for Linear Search using iterative approach
def linear_search(arr, target):
    # Traverse through all elements in the array
    for index in range(len(arr)):
        # If the element is found, return its index
        if arr[index] == target:
            return index
    # If the element is not found, return -1
    return -1

# Example usage:
arr = [10, 23, 45, 70, 11, 15]
target = 70

# Function call
result = linear_search(arr, target)

if result != -1:
    print(f"Element found at index: {result}")
else:
    print("Element not found in the array")

Output

Element found at index: 3

Python Program for Linear Search Recursive Approach

  • Base Case: If the index reaches the end of the list (index == len(arr)), the function returns -1, indicating that the target element is not found in the list.
  • Check Current Index: If the element at the current index matches the target, the function returns the index, indicating the position where the target was found.
  • Recursive Case: If the current element is not the target, the function recursively calls itself with the next index (index + 1) to continue the search.
  • Example Usage: The program searches for the target 30 in the list [10, 20, 30, 40, 50]. The function will find 30 at index 2 and return it.
Python
def linear_search_recursive(arr, target, index=0):
    # Base case: If index reaches the end of the list
    if index == len(arr):
        return -1  # Target not found
    
    # If the target is found at the current index
    if arr[index] == target:
        return index  # Return the index of the target
    
    # Recursive call to check the next element
    return linear_search_recursive(arr, target, index + 1)

# Example usage
arr = [10, 20, 30, 40, 50]
target = 30

result = linear_search_recursive(arr, target)

if result != -1:
    print(f"Element {target} found at index {result}.")
else:
    print(f"Element {target} not found in the list.")

Output

Element 30 found at index 2.

Time complexity: O(n). 

Auxiliary Space: O(1) for iterative and O(n) for recursive.

Please refer complete article on Linear Search and Difference Between Recursive and Iterative Algorithms for more details!

Python Program for Linear Search Using RegEx Method

This function takes a list lst and a pattern as input

  • re.compile(pattern): Compiles the given pattern into a regex object.
  • Iterate Over the List: The program iterates over each element in the list.
  • regex.search(element): Checks if the pattern exists within the current element.
  • Return Result: If a match is found, it returns the element and its index; otherwise, it returns “Pattern not found in the list.”
Python
import re

def linear_search(lst, pattern):
    # Compile the pattern using re
    regex = re.compile(pattern)
    
    # Iterate over the list and check if the pattern matches any element
    for index, element in enumerate(lst):
        if regex.search(element):
            return f"Pattern found in element '{element}' at index {index}"
    
    return "Pattern not found in the list"

# Example list
my_list = ["apple", "banana", "cherry", "date", "elderberry"]

# Pattern to search for
pattern = "an"  # Searching for the substring 'an'

# Perform linear search
result = linear_search(my_list, pattern)

# Output the result
print(result)

Output

Pattern found in element 'banana' at index 1

Time Complexity: The time complexity of this program is O(n) because we need to traverse the entire list to convert it to a string and count the number of commas before the match. The search using regular expression can also take some time depending on the length of the string, but it is generally considered to be a fast operation.

Space Complexity: The space complexity of this program is O(n) because we need to store the entire list as a string in memory. Additionally, the regular expression module uses some memory for its operations. However, since the input size is relatively small in this case, the space complexity is not a major concern.



Next Article

Similar Reads

Practice Tags :
three90RightbarBannerImg