JavaScript implements sequential search

Ideas

  1. Iterate over the array
  2. Find the target element and return its subscript
  3. After the traversal is over, if the target value is not found, return-1

Time complexity : O(n)

achieve

Existing array [7, 5, 4, 15, 3, 9, 6, 12], search sequentially 3:

Array.prototype.sequentialSearch = function(item) {
    
    
    for (let i = 0; i < this.length; i++) {
    
    
        if (this[i] === item) return i;
    }
    return -1;
};

const res = [7, 5, 4, 15, 3, 9, 6, 12].sequentialSearch(3);
console.log(res);

Results of the:

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/114966435