forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinearSearcher.cs
54 lines (50 loc) · 1.6 KB
/
LinearSearcher.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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;
}
}
}