Linear or sequential search algorithm
Linear search is a simple searching algorithm that sequentially checks each element in a collection until the target element is found or the end of the collection is reached. It is applicable to both sorted and unsorted collections.
Here's an example of a C# program that demonstrates the linear search algorithm:
using System;
class Program
{
static void Main()
{
int[] arr = { 10, 25, 6, 18, 42, 7 };
int target = 18;
int index = LinearSearch(arr, target);
if (index != -1)
{
Console.WriteLine($"Element {target} found at index {index}");
}
else
{
Console.WriteLine("Element not found");
}
}
static int LinearSearch(int[] arr, int target)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == target)
{
return i; // Return the index if the element is found
}
}
return -1; // Return -1 if the element is not found
}
}
Let's break down the linear search algorithm step by step:
-
We have an array arr containing elements and a target value that we want to find (target = 18).
We start with the first element of the array (arr[0] = 10) and compare it with the target value. Since 10 is not equal to the target (18), we move to the next element.
-
We compare the second element (arr[1] = 25) with the target value. Again, 25 is not equal to the target (18), so we move to the next element.
-
We continue this process, comparing each element of the array with the target value until we either find a match or reach the end of the array.
-
In this case, when we reach the fourth element (arr[3] = 18), we find a match. The element 18 is equal to the target value (18).
-
We return the index of the matched element, which is 3 in this case, indicating that the target element was found at index 3.
-
The program then outputs: "Element 18 found at index 3".
In the given example, the target element is 18. The program will output:
Element 18 found at index 3
If the target value is not found in the array, the linear search algorithm will iterate through all the elements without finding a match. In that case, it returns -1 to indicate that the target element is not present in the array.