3.7.2 Search Algorithms
Algorithms and Problem Solving
Search algorithms are designed to find specific elements or a set of elements within a dataset. They are critical for tasks such as information retrieval, database queries, and decision-making processes.
3.7.2.1 Linear Search
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!