Lesson 3: Introduction to Linear Search Algorithms
What is a linear search algorithm?
A linear search algorithm is the simplest way to search for an element contained in a dataset. It is the least efficient algorithm search method as you are sequentially searching for an item that may be last in the array or not in the array at all. In that case, the algorithm searches through the whole array before it returns the item that you are looking for.
Examples of linear search algorithms
Example 1
Element "66" must be linear searched in the below array of numbers.
Step 1: Element "66" is compared with the first position (0) in the array, which is 22. 66 ≠ 22
Step 2: Element "66" is compared to the second position (1) in the array, which is 88. 66 ≠ 88
Step 3: Element "66" is compared to the third position (2) in the array, which is 66. 66 = 66 A match is found, and the linear search algorithm is finished.
Example 2
The following code, implementing a linear search algorithm, is from a Section B long question from the 2020 Leaving Certificate Computer Science exam paper:
When a name is inserted, the algorithm runs and stops when the inserted name is found or not found. Either way, the number of times the algorithm runs through each name is recorded.
Real Life Example
You are at a library looking for a specific book in a section. To find the book, you search through each book in the section it is in, one by one, eliminating each passing book until you find it. The book you are searching for may be the first book you pick up or the last. That is the risk that you take with the linear search method. It has the potential to be very time-consuming.
Advantages of linear search algorithms
It is effective for arrays with a small amount of data. With the linear search algorithm method, the data that is required does not need to be sorted, unlike the binary search algorithm method.
Key Terms
- Linear
- Sequentially
- Array