Python – Linear Search Algorithm

Python – Linear Search Algorithm

Linear Search is a simple searching algorithm that iterates through each element in a list or array to find a specific value. It sequentially checks each element until a match is found or the entire list is traversed.

Linear Search is straightforward but may not be the most efficient for large datasets compared to other searching algorithms like binary search. However, it is effective for unsorted or small datasets.

Algorithm Steps

The steps of the Linear Search algorithm are as follows:

  1. Start from the first element of the list.
  2. Compare the target value with the current element.
  3. If the values match, return the index of the current element.
  4. If the values do not match, move to the next element in the list.
  5. Repeat steps 2-4 until a match is found or the end of the list is reached.
  6. If the end of the list is reached without finding a match, return an indication that the value is not in the list.

Python Program for Linear Search

In the following program, we define a function linear_search() that takes an array and target element as arguments, finds the index of the target element, and returns the index. If the target element is not present in the array, then it returns -1.

Python Program

def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

if __name__ == "__main__":
    my_list = [10, 5, 8, 12, 7, 3, 1]
    target_value = 7
    result = linear_search(my_list, target_value)
    print(f"Index of target {target_value} in the array is: {result}")

Output

Index of target 7 in the array is: 4

Explanation

[10, 5, 8, 12, 7, 3, 1]  ← array
               ↑ target element
  0  1  2   3  4  5  6   ← indices
               ↓
             index of target element

References for program

Use Cases for Linear Search

Linear Search is suitable for various scenarios, including:

  • Searching for an element in an unsorted list.
  • Finding the first or all occurrences of a specific value.
  • Checking if a value exists in a collection.
  • Searching through small datasets where simplicity is more important than efficiency.

Summary

Linear Search is a fundamental and easy-to-understand algorithm for searching through a list or array. In this tutorial, we have learnt the steps for Linear Search, defined a Python function that implements the Linear Search algorithm, and seen its usage.

Code copied to clipboard successfully 👍