-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearch.cs
More file actions
63 lines (61 loc) · 2.16 KB
/
LinearSearch.cs
File metadata and controls
63 lines (61 loc) · 2.16 KB
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
55
56
57
58
59
60
61
62
63
using System;
namespace DA.Algorithms.Search
{
public static class LinearSearch
{
/// <summary>
/// Find value in an unsorted collection
/// and return true if the value exists, otherwise return false.
/// <para>Time Complexity - O(n). No extra memory is used to allocate the array.</para>
/// </summary>
///
/// <typeparam name="T">base type of elements in an array</typeparam>
/// <param name="array">collection of an elements.</param>
/// <param name="value">target value to find</param>
///
/// <returns>
/// true - if the value exists.
/// false - if the value doesn't exist.
/// </returns>
public static bool SearchUnsortedInput<T> (T[] array, T value) where T : IEquatable<T>
{
for (int current = 0; current < array.Length; current++)
{
if (value.Equals (array[current]))
{
return true;
}
}
return false;
}
/// <summary>
/// Find value in a sorted collection
/// and return true if the value exists, otherwise return false.
/// <para>Time Complexity - O(n). No extra memory is used to allocate the array.</para>
/// </summary>
///
/// <typeparam name="T">base type of elements in an array</typeparam>
/// <param name="array">collection of an elements.</param>
/// <param name="value">target value to find</param>
///
/// <returns>
/// true - if the value exists.
/// false - if the value doesn't exist.
/// </returns>
public static bool SearchSortedInput<T> (T[] array, T value) where T : IComparable<T>
{
for (int current = 0; current < array.Length; current++)
{
if (value.CompareTo (array[current]) == 0)
{
return true;
}
else if (value.CompareTo (array[current]) < 0)
{
return false;
}
}
return false;
}
}
}