🔍 The Quest for Information
Imagine trying to find a specific book in a massive, unorganized library. How would you do it? In programming, we often face similar tasks: finding specific data within collections like lists or arrays.
An algorithm is just a set of steps to solve a problem. A search algorithm provides the steps to find an item. Let's start with the most straightforward one: Linear Search.
🚶 What is Linear Search?
It's like checking items one by one, in order.
The Goal
You have a list of items and a specific item (target) you're looking for.
The Process
Start at the beginning. Check the first item. Is it the target? No? Check the second. Repeat.
The Result
Stop when you find the target (Success!) or when you've checked every item (Not Found).
Simple, intuitive, but can be slow for very large, unsorted lists.
⚙️ How It Works: Step-by-Step
Let's visualize searching for the number 42 in a list: [10, 5, 42, 19, 8].
Start at Index 0
Look at the first item: 10. Is it 42? No.
Move to Index 1
Look at the next item: 5. Is it 42? No.
Move to Index 2
Look at the next item: 42. Is it 42? Yes!
Target Found!
Stop searching. The item was found at index 2.
This required checking 3 items.
🐍 Linear Search in Python
Here's how you might write a simple linear search function.
def linear_search(data_list, target):
for index in range(len(data_list)): # Loop through indices
if data_list[index] == target: # Check item at current index
return index # Found it! Return the index
return None # Went through the whole list, not found
# Example usage:
my_list = [10, 5, 42, 19, 8]
found_at = linear_search(my_list, 42) # found_at will be 2
not_found = linear_search(my_list, 99) # not_found will be None
This function takes a list (`data_list`) and the item to find (`target`) as input.
It uses a for loopRepeats code for each item in a sequence (here, indices 0, 1, 2...) with `range(len(data_list))` to get each index number (0, 1, 2, etc.) of the list.
Inside the loop, an if statementChecks if a condition is true. compares the element at the current `index` (`data_list[index]`) with the `target`.
If they match, the function immediately stops and returns the indexSends the index back as the result.. If the loop finishes without finding the target, it returns NoneA special value indicating 'nothing' or 'not found'..
🧠 Quick Check!
Module 27 Theory Complete!
You've grasped the basics of Linear Search! It's a fundamental building block.
Ready to practice implementing it or explore more advanced concepts?