Linear Search
Linear Search is a simple searching algorithm that sequentially checks each element in a collection until the desired element is found or the entire collection has been searched.
How Linear Search Works
-
Starting at First Element:
- Begin searching from the first element of the collection.
-
Sequential Checking:
- Check each element one by one until a match is found.
-
Completion:
- Stop searching if the element is found or if the end of the collection is reached.
Key Features
- Simple and Intuitive: Linear Search is easy to implement and understand.
Efficiency
- Time Complexity: O(n) where n is the number of elements in the collection.
- Space Complexity: O(1) as it doesn't require additional memory.
Advantages
- Easy to implement and understand.
- Works well for small collections.
Disadvantages
- Inefficient for large collections.
- Takes linear time for search in worst-case scenarios.
Linear Search Implementation in JavaScript
Here's an example of Linear Search implemented in JavaScript:
Sorting-Algo/lis.js
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i; // Found at index i
}
}
return -1; // Not found
}
// Example usage
const array = [10, 20, 30, 40, 50];
const target = 30;
const index = linearSearch(array, target);
console.log("Index of", target, ":", index);