sequential search
What is sequential search?
Sequential search is a relatively inefficient search algorithm, but it is relatively simple to implement. The main steps are as follows:
- iterate over the array
- Find an element equal to the target value, and return its subscript
- After the traversal, if the target value is not found, return -1
base case
- Time complexity: O(n)
- Space Complexity: O(1)
Array.prototype.sequentialSearch = function (target) {
for (let i = 0; i < this.length; i++) {
if (this[i] === target) {
return i
}
}
return -1
}
const res = [1, 2, 3, 4, 5].sequentialSearch(1) // 0
Since the array is traversed in the code, the time complexity is O(n). And the space complexity is O(1) because no variables are used which grow linearly.
Original Link: Vegetable Garden Front End