JavaScript Sequential Search Algorithm Example

const DOES_NOT_EXIST = -1;

function sequentialSearch(array, value, equalsFn = defaultEquals) {
  for (let i = 0; i < array.length; i++) {
    if (equalsFn(value, array[i])) {
      return i;
    }
  }
  return DOES_NOT_EXIST;
}

function defaultEquals(a, b) {
  return a === b;
}

let array = [2,1,5,4,3,8,7,6];
let value = 6;
let index = sequentialSearch(array, value);
console.log("index of element " + index);
Output:
index of element 7

Comments