JavaScript 实现顺序搜索

思路

  1. 遍历数组
  2. 找到跟目标元素,返回它的下标
  3. 遍历结束后,若没有找到目标值,返回-1

时间复杂度:O(n)

实现

现有数组[7, 5, 4, 15, 3, 9, 6, 12],进行顺序搜索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);

执行结果:

猜你喜欢

转载自blog.csdn.net/Jack_lzx/article/details/114966435