3.7.2.1 Linear Search
Algorithms and Problem Solving
A linear search is a straightforward method for finding an item in a list. You check each item one by one until you find what you're looking for. Here's how it works,
- Start at the Beginning: Look at the first item in the list.
- Check Each Item: Compare the item you're looking for with the current item.
- Move to the Next: If they don't match, move to the next item in the list.
- Repeat: Continue this process until you find the item or reach the end of the list.
Example: Suppose you have a list of city names: [Karachi, Lahore, Islamabad, Faisalabad] And you want to find out if Islamabad is in the list.
- Start with Karachi. Since Karachi isn't Islamabad, move to the next city.
- Next is Lahore. Lahore isn't Islamabad, so move to the next city.
- Now you have Islamabad. This is the city you're looking for!
In this case, you've found Islamabad in the list. If Islamabad weren't in the list, you would check all the cities and then conclude that it's not there. This method is called a linear search because you check each item in a straight line, from start to finish.