Skip to content

Latest commit

 

History

History
26 lines (18 loc) · 707 Bytes

linearSearch.md

File metadata and controls

26 lines (18 loc) · 707 Bytes

Linear search

Most basic search algorithm. It sequentially moves through your collection / array looking for a matching value.

The worst case scenario for a linear search is that it needs to loop through the entire collection to find a match, either because the item we are looking for is the last one or because it doesn't exist.

Linear search gif

Example in JavaScript:

const numbers = [8,4,5,3,1,9];

const linearSearch = numberToFind => {
  for(let i = 0; i <= numbers.length; i++){
    if(numbers[i] === numberToFind){
      return i;
    }
  }
}

linearSearch(9); // returns the index 5.