Linear search facts for kids
Linear search (also called sequential search) is a simple way to find an item in a list. Imagine you have a list of names, and you want to see if "Alice" is on it. Linear search means you start at the very beginning of the list and check each name one by one until you find "Alice" or reach the end of the list. It's a basic search algorithm that computers can use.
How Linear Search Works
Let's say you have a list of items, and you are looking for a specific one. Here's how linear search finds it:
- First, check if your list is empty. If it is, then the item you are looking for cannot be there. So, you stop.
- If the list is not empty, you start looking at the very first item.
- You check each item one by one:
- If the item you are looking at is the one you want, great! You found it. You stop searching and remember where it was in the list (its position).
- If the item is not the one you want, you move on to the next item in the list.
- If you have checked every single item in the list and still haven't found what you're looking for, then the item is not in the list. You stop searching.
Linear Search in Code
Computers can use linear search too! Here's an example of how it might look in the Java programming language. This piece of code is called a method. It takes two pieces of information (called parameters):
- An array (which is like a list) of integers (whole numbers).
- The specific integer (number) you are trying to find.
The code will tell you the position of the item if it finds it. If it doesn't find the item, it will say -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