Algo Spectrum

Table of Contents

  • Algorithms
    • Searching Algorithms
      • Linear Search
        • Algorithm Overview
        • Example
        • Implementation in Python
        • Usage
      • Sentinel Linear Search
      • Binary Search
      • Jump Search
    • Sorting Algorithms
    • Mathematical Algorithms
  • Data Structure

Packages and Modules:

  • algo_spectrum
Algo Spectrum
  • Algorithms
  • Searching Algorithms
  • Linear Search
  • Edit on GitHub

Linear Search

algorithms.linear_search()

The Linear Search algorithm, also known as Sequential Search, is a simple searching algorithm that sequentially checks each element of a collection until a match is found or the entire collection is traversed.

Algorithm Overview

Linear Search Flow Diagram

  1. Start with the first element of the collection.

  2. Compare the target element with the current element.

  3. If a match is found, return the index of the current element.

  4. If the target element is not found, move to the next element and repeat steps 2-3.

  5. Continue this process until the target element is found or the end of the collection is reached.

Note

Linear Search has a time complexity of O(n), where ‘n’ is the number of elements in the collection.

Example


Implementation in Python

Here’s a Python implementation of the Linear Search algorithm:

1 def linear_search(target: Any, items: List[Any]) -> Optional[int]:
2     for i, num in enumerate(arr):
3         if num == target:
4             return i
5     return None

Usage

To use the linear_search function:

 1 from algorithms import linear_search
 2
 3
 4 arr = [4, 2, 7, 1, 9, 5]
 5 target = 7
 6 index = linear_search(arr, target)
 7 if index:
 8     print(f"Element {target} found at index {index}")
 9 else:
10     print(f"Element {target} not found")
Previous Next

© Copyright 2024, Supreet Praharaj.

Built with Sphinx using a theme provided by Read the Docs.