Linear Search Algorithm
Searching is the process of finding a specific value in a collection of data, such as an array. Two common search algorithms are linear search and binary search.
Both algorithms look for a target value, but they do so in different ways. Choosing the right algorithm depends on how the data is organized.
Linear Search
A linear search checks each element one at a time, starting at the beginning of the array.
If the current element matches the target value, the search stops. Otherwise, the algorithm continues to the next element until it finds the target or reaches the end of the array.
For example, suppose you want to find the value 18.
A linear search checks the values in this order:
- Check
12. - Check
7. - Check
18. The value is found.
Because linear search examines one element at a time, it works with any array, whether the values are sorted or not.
When to Use Linear Search
Linear search is a good choice when:
- the array is small
- the data is not sorted
- simplicity is more important than speed
Your Turn
Let's try it in the Java Playground.
- Trace and predict the output of the code. Run the code to test your prediction.
- Change the value being searched for to a value not in the list. What should be returned? Run the code to test your prediction.
- Modify the array
valuesso that it contains duplicate values of what you are looking for. What will be returned? Run the code to test your prediction.