linear search in 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;
}