Linear search

Easy TimeO(n) SpaceO(1)

Given an array arr, in no particular order, and a target, return the index of the first element equal to it, or -1 when it never appears. Comparison is by value.

Examples

Example 1

Input
arr = [4, 2, 7, 1, 9]target = 7
Output
2
7 sits at index 2, after the 4 and the 2.

Example 2

Input
arr = [2, 7, 2]target = 2
Output
0
2 is at index 0 and again at index 2, and the first one is wanted.

The Code

function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) return i;
  }
  return -1;
}
linearSearch([4, 2, 7, 1, 9], 7);
Done
Step through linearSearch([4, 2, 7, 1, 9], 7) call by call