Linear search

From Wikipedia, the free encyclopedia
Jump to: navigation, search

Linear search or sequential search is an algorithm to find an item in a list. It's a search algorithm.

The algorithm in pseudo code[change | edit source]

Start out with a list, L which may have the item in question.

  1. If the list, L is empty, then the list has nothing. The list does not have the item in question. Stop here.
  2. Otherwise, we look at all the elements in the list, L.
  3. For each element:
    1. If the element equals the item in question, the list HAS the item in question. Stop here.
    2. Otherwise, go onto next element.
  4. The list does not have the item in question.

Linear search in Java[change | edit source]

In the programming language Java, linear search looks like this. This method has two parameters: an array of integers and the item we are looking for (also an integer). It says the location in the array if it finds the item. If it does not find it, it says -1.

public int getItem(int[] list, int item) {
  for (int i = 0; i < list.length; i++) {
    if (list[i] == item)
      return i;
  }
  return -1;
}