Mental Model
Look at each item one by one until you find the one you want or reach the end.
Analogy: Imagine looking for a book on a shelf by checking each book from left to right until you find it.
[5] -> [3] -> [7] -> [1] -> [9] -> null ↑
[5] -> [3] -> [7] -> [1] -> [9] -> null ↑
[5↑] -> [3] -> [7] -> [1] -> [9] -> null
[5] -> [3↑] -> [7] -> [1] -> [9] -> null
[5] -> [3] -> [7↑] -> [1] -> [9] -> null
[5] -> [3] -> [7] -> [1↑] -> [9] -> null
[5] -> [3] -> [7] -> [1↑] -> [9] -> null Found value 1 at index 3
class LinearSearch { static search(arr, target) { for (let i = 0; i < arr.length; i++) { if (arr[i] === target) { return i; // found target at index i } } return -1; // target not found } } const array = [5, 3, 7, 1, 9]; const target = 1; const index = LinearSearch.search(array, target); if (index !== -1) { console.log(`Found value ${target} at index ${index}`); } else { console.log(`Value ${target} not found`); }
for (let i = 0; i < arr.length; i++) {if (arr[i] === target) {return i; // found target at index ireturn -1; // target not foundfor (let i = 0; i < arr.length; i++) {
return -1; // target not found
if (arr[i] === target) {Linear Search Algorithm?arr?const arr = [4, 8, 15, 16, 23, 42];
function linearSearch(array, target) {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) {
return i;
}
}
return -1;
}
console.log(linearSearch(arr, 15));function linearSearch(arr, target) {
for (let i = 0; i <= arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}[3, 5, 7, 7, 9] using linear search. Which code snippet correctly returns the index of the first 7?Pass the test and this pattern moves unknown