Linear search facts for kids
Linear search or sequential search is a method to find an item in a list. It is a search algorithm.
Contents
Algorithm
Start out with a list, L
which may have the item that we want to look for.
- If the list
L
is empty, then the list has nothing. The list does not have the item that we are looking for, so we stop here. - If the list
L
is not empty, we look at all the elements in the list. - For each element:
- If the element equals the item that we are looking for, the list has the item in question, so we will stop here and return the position in the list that has the element that we are looking for.
- If not, we will go on to the next element.
- When we reached the end of the list and still have not found the element that we are looking for, then the list does not have the item that we want.
Implementation
In the Java programming language, 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 linearSearch(int[] list, int item) {
for (int i = 0; i < list.length; i++) {
if (list[i] == item) {
return i;
}
}
return -1;
}
Related pages
See also
In Spanish: Búsqueda lineal para niños
All content from Kiddle encyclopedia articles (including the article images and facts) can be freely used under Attribution-ShareAlike license, unless stated otherwise. Cite this article:
Linear search Facts for Kids. Kiddle Encyclopedia.