linear search javascript code example

Example 1: linear search js

//  arr.indexOf(val)
function linearSearchIndexOf(arr, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === val) {
      return i;
    }
  }
  return -1;
}

//  arr.includes(val)
function linearSearchIncludes(arr, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === val) {
      return true;
    }
  }
  return false;
}

//  arr.find(cb)
//  cb = CallBack Function

function linearSearchFind(arr, cb) {
  for (let i = 0; i < arr.length; i++) {
    if (cb(arr[i]) === true) {
      return arr[i];
    }
  }
  return undefined;
}

Example 2: linear search javascript

function searchAlgorithm (number){
 
    for(let i = 0; i< number; i++){
    if(number == array[i]){
      console.log("Found it, it's at index " + i)
    }else{
      console.log("Not found")
    }
    
  };
  
}


var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

searchAlgorithm(5)

Tags:

Misc Example