Course contentsShow
← Computer Science
Lesson 250 of 2,8726. Arrays and Basic CollectionsFree lesson

Linear Search: Sequential Element Finding

Search arrays element-by-element from start to end, understanding O(n) complexity and when linear search is appropriate.

Linear Search: Sequential Element Finding

You'll learn how to search through an array one element at a time, understanding when this simple approach makes sense.

What is Linear Search?

Linear search is the most straightforward way to find an element in an array: start at the beginning and check each element one-by-one until you find what you're looking for (or reach the end). Think of it like looking for a specific book on a shelf by examining each book from left to right until you spot the right one.

How It Works

When you perform a linear search:

  1. Start at index 0
  2. Compare the current element with your target value
  3. If they match, you've found it—return the index
  4. If not, move to the next element
  5. Repeat until you find the target or run out of elements

If you reach the end without finding the target, the element doesn't exist in the array (often indicated by returning -1).

numbers = [10, 23, 5, 42, 17]
target = 42

for i in range(len(numbers)):
    if numbers[i] == target:
        print(f"Found at index {i}")
        break
else:
    print("Not found")

Time Complexity: O(n)

Linear search has O(n) complexity, meaning in the worst case, you'll check every element. With 100 elements, you might need 100 comparisons. It's slow for large arrays but perfectly fine for small ones or when data isn't sorted.

When to Use Linear Search

  • Small arrays where simplicity matters more than speed
  • Unsorted data (other search methods require sorting first)
  • When you only search occasionally

Key Takeaway: Linear search checks each array element sequentially until finding the target, taking O(n) time—simple but potentially slow for large datasets.