linear search js 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)

Example 3: JavaScript Implementation of Linear Search

function linearSearch(value, list) {
    let found = false;
    let position = -1;
    let index = 0;
 
    while(!found && index < list.length) {
        if(list[index] == value) {
            found = true;
            position = index;
        } else {
            index += 1;
        }
    }
    return position;
}

Example 4: JavaScript Implementation of Linear Search

Set found to false
Set position to −1
Set index to 0
while found is false and index < number of elements
    if list[index] is equal to search value
        Set found to true
        Set position to index
    else Add 1 to index
return position