Linear Search
Linear Search
Let’s say we have array[] that consists of n elements.
And now our task is to write a method that will find the element selected by us in this array.
Data:
Let’s say we have an array with this data.
Array[] = {30, 60, 80, 90, 130, 150, 210, 260, 400, 460, 20, 90, 50, 330, 220}
Purpose, Assumptions:
And we are looking for the element = 50,
So the answer should be the index of this element = 12,
And when we look for an element in this array that is not in it, e.g. 100
in response we should get the index of this element = -1
which will mean that such an element is not in the array.
Solution:
A simple approach to doing this is to perform a linear search.
We start with the leftmost element of array[] and take turns comparing the search element to each element in array[].
If the searched element matches an element of the array, the index of that element is returned. If the searched element does not match any of the elements, we return -1,
which tells us that the element we are looking for is not in the array.
Implementation in C# code
public static void Main()
{
int[] array = { 30, 60, 80, 90, 130, 150, 210, 260, 400, 460, 20, 90, 50, 330, 220 };
int theElementLookingFor = 50;
int result = LinearSearch(array, theElementLookingFor);
if (result == -1)
Console.WriteLine(@"Element {0} is not in the array", theElementLookingFor);
else
Console.WriteLine("Element {0} is present at index in the array {1}", theElementLookingFor, result);
}
private static int LinearSearch(int[] array, int theElementLookingFor)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] == theElementLookingFor)
return i;
}
return -1;
}
Output:
Element 50 is not in the array 12 or Element 100 is not in the array