Linear search
From Simple English Wikipedia, the free encyclopedia
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.
- If the list, L is empty, then the list has nothing. The list does not have the item in question. Stop here.
- Otherwise, we look at all the elements in the list, L.
- For each element:
- If the element equals the item in question, the list HAS the item in question. Stop here.
- Otherwise, go onto next element.
- 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; }