Sequential search algorithm!

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:

  1. iterate over the array
  2. Find an element equal to the target value, and return its subscript
  3. 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

Guess you like

Origin blog.csdn.net/qq2603375880/article/details/131665458