-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cs
More file actions
98 lines (90 loc) · 2.92 KB
/
BinarySearch.cs
File metadata and controls
98 lines (90 loc) · 2.92 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
namespace DA.Algorithms.Search
{
public static class BinarySearch
{
/// <summary>
/// Find value in a sorted collection
/// and return true if a value exists, otherwise return false.
/// <para>Time Complexity - O(logn)</para>
/// </summary>
///
/// <exception cref="ArgumentNullException"/>
///
/// <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 Search<T> (T[] array, T value) where T : IComparable<T>
{
if (array == null)
{
throw new ArgumentNullException ();
}
int low = 0;
int high = array.Length - 1;
int middle;
while (low <= high)
{
middle = low + (high - low) / 2;
if (array[middle].CompareTo (value) == 0)
{
return true;
}
else if (array[middle].CompareTo (value) < 0)
{
low = middle + 1;
}
else
{
high = middle - 1;
}
}
return false;
}
/// <summary>
/// Recursively find value in a sorted collection
/// and return true if a value exists, otherwise return false.
/// <para>Time Complexity - O(logn)</para>
/// </summary>
///
/// <exception cref="ArgumentNullException"/>
///
/// <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 Search<T> (T[] array, T value, int lowIndex, int highIndex) where T : IComparable<T>
{
if (array == null)
{
throw new ArgumentNullException ();
}
if (lowIndex > highIndex)
{
return false;
}
int middle = lowIndex + (highIndex - lowIndex) / 2;
if (array[middle].CompareTo (value) == 0)
{
return true;
}
else if (array[middle].CompareTo (value) < 0)
{
return Search (array, value, middle + 1, highIndex);
}
else
{
return Search (array, value, lowIndex, middle - 1);
}
}
}
}