Linear search or sequential search is a method to find an item in a list. It is a search algorithm.
Start out with a list, L which may have the item that we want to look for.
L is empty, then the list has nothing. The list does not have the item that we are looking for, so we stop here.L is not empty, we look at all the elements in the list.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;
}
Implementing a linear search in .NET (C#) would look like this:
static int LinearSearch(int[] list, int item)
{
for (int i = 0; i < list.ToString().Length; i++)
{
if (list[i] == item)
{
return i;
}
}
return -1;
}
var searchContext = new[]
{
1,
2,
3
};
var example = LinearSearch(searchContext, 3);
Console.Write($"What you've searched for has returned '{searchContext[example]}'");
Console.Write($", at list index {example}.");