Searching algorithms are digital detectives that help computers find specific pieces of information within large datasets. Whether it's locating a name in a contact list or a value in an array, these algorithms are essential for efficiently retrieving data from computer systems. "In this article, we will delve into the concept of linear search."
The Story of Jhon and the Thief:
Once, a thief swiftly stole from a shop and vanished. Jhon witnessed it all and reported it to the police. Subsequently, Jhon faced a lineup of 50 people, carefully examining each face one by one to identify the thief. This systematic approach is similar to how we search for things step by step. This approach has a name in the world of computing—it's called a "linear search." In simple terms, it's like a computer checking items in a list, just like Jhon checking faces. This method is smart and effective, whether it's finding a culprit or searching for information on a computer.
What is Linear search?
A linear search is the basic method used to find an item in a dataset. It goes through each element one by one, starting from the beginning and stopping when it finds a match. Once the desired item is found, the search concludes.
Basic Steps of Linear Search Algorithm?
Start: Begin from the first element in the data collection (array or list).
Compare: Check if the current element matches the target element you're searching for.
Match Found: If a match is found, the search is successful, and you can stop the search.
Move Forward: If no match is found, move to the next element in the collection.
Repeat: Repeat steps 2-4 until either a match is found or you've checked all elements.
Search Complete: If you've checked all elements and haven't found a match, the search is unsuccessful.
Example of Linear search:
Let's take an example scenario where we have an array, and our goal is to determine if the number 50 is present within this array.
We start the search at index 0. Here, we find that 50 is not equal to 10, so we move to the next step.
Moving on to index 1, we compare 50 with 15 and again don't find a match. So, we proceed further.
At index 2, the comparison with 12 shows that 50 is not equal to 12, prompting us to continue.
Progressing to index 3, we see that 50 is not equal to 25, leading us to the next index.
Reaching index 4, the comparison with 30 demonstrates that 50 is not equal to 30. Therefore, we proceed once again.
Finally, at index 5, the comparison shows that 50 is indeed equal to 50. As a result, we can conclude that 50 has been found at index 5.
Consider another example: We're working with an array, aiming to determine if the number 13 exists within it.
We start at index 0, where 13 isn't equal to 10. Moving forward.
At index 1, 13 isn't equal to 15. Moving on.
Index 2 reveals that 13 isn't equal to 12. Onward.
At index 3, 13 isn't equal to 25. Advancing.
Index 4 shows that 13 isn't equal to 30. Continuing.
Index 5, 13 isn't equal to 50. Progressing.
Index 6 indicates that 13 isn't equal to 40. On we go.
Index 7 demonstrates that 13 isn't equal to 38. Moving ahead.
Index 8, 13 isn't equal to 60.
Since this is the last index (8), we conclude that the number 13 isn't present in the list.
Performance Analysis
Time Complexity:
Best Case O(1): When you find the item in the first position
Worst Case O(n): When you find the item at the last position
Average Case O(n): When you find the element in the middle of the array
Space Complexity: O(1)
Coding Implementation:
Implement using while loop:
// This function performs a linear search on an array to find a target element.
function linearSearch(arr, target) {
let index = 0; // Initialize an index to track the current position in the array.
while (index < arr.length) { // Start a loop that runs until the index is within array bounds.
if (arr[index] == target) { // Check if the element at the current index matches the target.
return index; // If a match is found, return the index where the target is located.
}
index++; // If target isn't found move to the next index to continue searching.
}
return -1; // If the loop completes without finding a match, return -1 to indicate not found.
}
console.log(linearSearch([10, 15, 12, 25, 30, 50, 40, 38, 60], 10)); // O(1) because target found at first attempt
console.log(linearSearch([10, 15, 12, 25, 30, 50, 40, 38, 60], 50)); // O(n) where n is the number of elements, as target is found in the middle
console.log(linearSearch([10, 15, 12, 25, 30, 50, 40, 38, 60], 13)); // O(n) where n is the number of elements, as target is not found
Implement using for loop:
// This function uses a linear search to find a target element in an array.
function linearSearch(arr, target) {
for (let index = 0; index < arr.length; index++) { // Loop through each index in the array.
if (arr[index] == target) { // Check if the current element matches the target.
return index; // If a match is found, return the index where the target is located.
}
}
return -1; // If no match is found, return -1 to indicate that the target is not in the array.
}
console.log(linearSearch([10, 15, 12, 25, 30, 50, 40, 38, 60], 10)); // O(1) because target found at first attempt
console.log(linearSearch([10, 15, 12, 25, 30, 50, 40, 38, 60], 50)); // O(n) where n is the number of elements, as target is found in the middle
console.log(linearSearch([10, 15, 12, 25, 30, 50, 40, 38, 60], 13)); // O(n) where n is the number of elements, as target is not found
When to Use Linear Search?
Unsorted Data: When your data is neither ascending nor descending order, you can use Linear search.
Small Data Sets: When dealing with relatively small datasets, making linear search a simple and efficient choice.
Real-world examples
Checking Names: Imagine you're checking attendance in a classroom. You go through the list of names one by one, checking who is present.
Supermarket Aisle: When searching for a particular item in a supermarket aisle, you might scan each product shelf one by one until you spot what you need.
Library Bookshelves: If you're at a library and want to find a specific book, you could go through the books on each shelf in order until you locate the book you're interested in.
Music Playlist: If you're listening to a playlist of songs and want to find a specific song, you might listen to each song in the order they appear until you reach the one you're looking for.
Contact List: Imagine you have a list of contacts on your phone. When you're trying to find a specific person's phone number, you might use linear search by scrolling through the list until you find the name you're looking for.
Use case in Programming
Finding an Element in an Array/List: Linear search can be used to find if a particular element exists in an array or a list. You iterate through each element and compare it with the target element until you find a match or exhaust the list.
Searching for Values in User Input: If a program needs to search for specific values entered by a user, like a username in a list of registered users, linear search can be employed to locate the input value.
Data Validation: In form validation, you might use linear search to check if a user-provided value matches an allowed set of values, like verifying a user's selected option from a predefined list.
Filtering Data: Linear search can be used to filter data based on specific criteria. For instance, finding all occurrences of a certain word in a text document.
Removing Duplicates: To remove duplicate values from an array or list, you can use linear search to iterate through the elements and eliminate duplicates as they are encountered.
Checking Prime Numbers: When checking if a number is prime, you might use linear search to verify if it's divisible by any number smaller than itself.
Implementing Other Algorithms: Some algorithms might require auxiliary tasks that involve linearly traversing data. For example, traversing an adjacency list in graph algorithms.
Our journey through linear search shows that simple can be powerful. From Jhon's tale to the code examples, we've seen that it's not just an algorithm—it's like an exciting discovery journey, much like life. As we finish, let's appreciate the smart simplicity of linear search and its impact in programming.