Linear Searcher Algorithm
The Linear Search Algorithm, also known as the Sequential Search Algorithm, is a fundamental searching technique used for finding a specific element within a list or an array of elements. The algorithm works by iterating through each element in the list or array, comparing it with the target value. If the element being examined matches the target value, the algorithm stops and returns the index of the matching element. If the algorithm reaches the end of the list or array without finding the target element, it returns an indication that the value was not found, such as -1 or null.
The primary advantage of the Linear Search Algorithm is its simplicity, as it requires no prior knowledge of the data structure or any specific ordering of the elements within the list or array. This makes it particularly useful for small datasets, unsorted lists, or when searching for multiple occurrences of a target value. However, the algorithm's performance can be quite slow for large datasets, as it has a worst-case time complexity of O(n), where n is the number of elements in the list or array. In such cases, more efficient search algorithms like Binary Search or Hash-based searching techniques can be employed for better performance.
using System;
using Utilities.Exceptions;
namespace Algorithms.Search
{
/// <summary>
/// Class that implements linear search algorithm.
/// </summary>
/// <typeparam name="T">Type of array element.</typeparam>
public class LinearSearcher<T>
{
/// <summary>
/// Finds first item in array that satisfies specified term
/// Time complexity: O(n)
/// Space complexity: O(1).
/// </summary>
/// <param name="data">Array to search in.</param>
/// <param name="term">Term to check against.</param>
/// <returns>First item that satisfies term.</returns>
public T Find(T[] data, Func<T, bool> term)
{
for (var i = 0; i < data.Length; i++)
{
if (term(data[i]))
{
return data[i];
}
}
throw new ItemNotFoundException();
}
/// <summary>
/// Finds index of first item in array that satisfies specified term
/// Time complexity: O(n)
/// Space complexity: O(1).
/// </summary>
/// <param name="data">Array to search in.</param>
/// <param name="term">Term to check against.</param>
/// <returns>Index of first item that satisfies term or -1 if none found.</returns>
public int FindIndex(T[] data, Func<T, bool> term)
{
for (var i = 0; i < data.Length; i++)
{
if (term(data[i]))
{
return i;
}
}
return -1;
}
}
}