Linear search

From Simple English Wikipedia, the free encyclopedia

This article's English may not be simple
The English used in this article may not be easy for everybody to understand.

You can help Wikipedia by making this page or section simpler.

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

[edit] The algorithm in psuedo code

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.


[edit] Linear search in Java

In the programming language Java, linear search looks like this. This method has two parameters: an array of integers and the item we're looking for (also an integer). It says the location in the array if it finds the item. If it doesn't 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;
}