Answers for "linear search js"

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;
}
Posted by: Guest on June-19-2020
1

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)
Posted by: Guest on April-17-2020
1

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;
}
Posted by: Guest on June-11-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language