const array = [3, 8, 12, 6, 10, 2];
// Find 10 in the given array.
function checkForN(arr, n) {
for(let i = 0; i < array.length; i++) {
if (n === array[i]) {
return `${true} ${n} exists at index ${i}`;
}
}
return `${false} ${n} does not exist in the given array.`;
}
checkForN(array, 10);
function linearSearch(array, key){
for(let i = 0; i < array.length; i++){
if(array[i] === key) {
return i;
}
}
return -1;
}
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
function linearSearch(arr, item) {
// Go through all the elements of arr to look for item.
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) { // Found it!
return i;
}
}
// Item not found in the array.
return null;
}