Skip to Content

Linear Search

Linear search known as sequential search. It is a simple searching algorithm that checks every element in a list or array one by one until it finds the target value or reaches the end of the list.

Of course, Linear Search is not the most efficient for large datasets, but it does not require the data to be sorted and is easy to implement.

How it works?

Assuming we have an array [4, 2, 7, 1, 3] and we are searching for the target value 1:

  • We start at the first element (4) and compare it to the target (1). Since they are not equal, we move to the next element.
  • We compare the second element (2) to the target (1). Again, they are not equal, so we move on.
  • We compare the third element (7) to the target (1). Still not equal, so we continue.
  • We compare the fourth element (1) to the target (1). This time, they are equal, so we have found the target at index 3.

Implementation

linear_search.py
def linear_search(arr: list, target: int) -> int: for index, value in enumerate(arr): if value == target: return index return -1 data = [4, 2, 7, 1, 3] search_target = 1 result = linear_search(data, search_target) if result != -1: print(f"Element {search_target} found at index {result}.") else: print(f"Element {search_target} not found in the array.")

Visualization

Linear Search Visualization
36
[0]
78
[1]
51
[2]
23
[3]
23
[4]
Comparisons: 0
Idle
Searching
Found
Not Found
Search Controls
Algorithm Info

Linear Search

Linear Search sequentially checks each element of the array until a match is found or the entire array has been searched. It's the simplest search algorithm but not the most efficient for large datasets.

Time Complexity

  • Best Case: O(1) - Element found at first position
  • Average Case: O(n) - Element in middle
  • Worst Case: O(n) - Element at end or not present

Space Complexity

O(1) - No extra space required

Use Cases

Best for small datasets or unsorted arrays where other search algorithms cannot be applied.

Last updated on