Linear Search

Ayumi Tanaka
Algorithm Novice
Published in
Sep 30, 2020

Q. Write an algorithm that performs linear search on a given array.

let testArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 19, 24, 29, 39, 45]
const linearSearch = function(arr, target) { for (let i = 0; i < arr.length; i++) { if (target === arr[i]) { return i; } }};
console.log(linearSearch(testArray, 3)); // should be 2
  1. Return i if target is equal to arr[i].
  2. Iterate 1. until i become to be equal to arr.length-1. (Which means it would be conditioned i < arr.length)
1st loopi = 0
target !== testArray[0] // 3 !== 1 False
2nd loopi = 1
target !== testArray[1] // 3 !== 2 False
3rd loopi = 2
target === testArray[2] // 3 === 3 True
Return i = 2

--

--