Introduction
Linear search, also known as sequential search, is a straightforward search algorithm used to find a particular value within a list. It works by checking each element of the list, one by one, until the desired value is found or the end of the list is reached.
Here's a step-by-step description of how linear search works.
- Start at the beginning: Begin with the first element of the list.
- Compare each element: Compare the current element with the target value.
- If a match is found: If the current element matches the target value, return the index of that element.
- Move to the next element: If the current element does not match the target value, move to the next element in the list.
- Repeat: Repeat steps 2-4 until either a match is found or the end of the list is reached.
- End of the list: If the end of the list is reached without finding a match, return a value (commonly -1) indicating that the target value is not present in the list.
Linear search is simple to implement but not very efficient for large lists because it potentially examines every element. Its time complexity is O(n), where n is the number of elements in the list, meaning that in the worst case, it takes time proportional to the size of the list.
Here is an example implementation in JavaScript.
function linearSearch(arrays, value) {
for (let i = 0; i < arrays.length; i++) {
if (arrays[i] === value) {
return i; // Return the index of the found value
}
}
return -1; // Return -1 if the value is not found
}
let arrays = [0, 1, 4, 5, 7, 98, 45, 6, 25, 3, 4, 5, 68, 9, 4, 2, 5, 77];
let value = 98;
let data = linearSearch(arrays, value);
console.log(data); // Output: 5