implementing searching algorithms in js code example
Example 1: linear search js
function linearSearchIndexOf(arr, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return -1;
}
function linearSearchIncludes(arr, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return true;
}
}
return false;
}
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)