Linear Search in Python Program

Linear search is a simple searching algorithm that checks each element in a list sequentially until the target element is found or the entire list is traversed. It's the most straightforward search method but not the most efficient for large datasets.

Algorithm

  • Start from the leftmost element of the given array and compare the target element x with each element one by one

  • If x matches with any element, return its index position

  • If x doesn't match with any elements in the array, return -1 or "element not found"

Visual Representation

Here's how linear search works step by step ?

t Index 0 u Index 1 t Index 2 o Index 3 r Index 4 i Index 5 a Index 6 l Index 7 Searching for: 'a' Found at Index 6! Search Direction ?

Implementation

Here's the basic linear search implementation ?

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

# Example usage
arr = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']
x = 'a'
result = linearsearch(arr, x)

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

Example with Numbers

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

# Searching in a numeric array
numbers = [10, 20, 30, 40, 50]
target = 30

result = linearsearch(numbers, target)
print(f"Number {target} found at index: {result}")

# Searching for a non-existent element
target_missing = 99
result_missing = linearsearch(numbers, target_missing)

if result_missing == -1:
    print(f"Number {target_missing} not found in the array")
Number 30 found at index: 2
Number 99 not found in the array

Time and Space Complexity

Complexity Best Case Average Case Worst Case
Time O(1) O(n) O(n)
Space O(1)

When to Use Linear Search

Linear search is ideal for:

  • Small datasets - When the array size is small

  • Unsorted data - When the array is not sorted

  • Simple implementation - When you need a quick, straightforward solution

  • One-time searches - When sorting overhead isn't justified

Conclusion

Linear search is a fundamental searching algorithm that works by checking each element sequentially. While it has O(n) time complexity, it's simple to implement and works on both sorted and unsorted arrays, making it suitable for small datasets or when simplicity is preferred over efficiency.

Updated on: 2026-03-25T06:31:59+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements