- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathBinarySearcher.cs
109 lines (97 loc) · 2.93 KB
/
BinarySearcher.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
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
99
100
101
102
103
104
105
106
107
108
109
usingSystem;
usingSystem.Collections;
usingSystem.Collections.Generic;
usingAlgorithms.Sorting;
namespaceAlgorithms.Search
{
publicclassBinarySearcher<T>:IEnumerator<T>
{
privatereadonlyIList<T>_collection;
privatereadonlyComparer<T>_comparer;
privateT_item;
privateint_currentItemIndex;
privateint_leftIndex;
privateint_rightIndex;
/// <summary>
/// The value of the current item
/// </summary>
publicTCurrent
{
get
{
return_collection[_currentItemIndex];
}
}
objectIEnumerator.Current=>Current;
/// <summary>
/// Class constructor
/// </summary>
/// <param name="collection">A list</param>
/// <param name="comparer">A comparer</param>
publicBinarySearcher(IList<T>collection,Comparer<T>comparer)
{
if(collection==null)
{
thrownewNullReferenceException("List is null");
}
_collection=collection;
_comparer=comparer;
HeapSorter.HeapSort(_collection);
}
/// <summary>
/// Apply Binary Search in a list.
/// </summary>
/// <param name="item">The item we search</param>
/// <returns>If item found, its' index, -1 otherwise</returns>
publicintBinarySearch(Titem)
{
boolnotFound=true;
if(item==null)
{
thrownewNullReferenceException("Item to search for is not set");
}
Reset();
_item=item;
while((_leftIndex<=_rightIndex)&¬Found)
{
notFound=MoveNext();
}
if(notFound)
{
Reset();
}
return_currentItemIndex;
}
/// <summary>
/// An implementation of IEnumerator's MoveNext method.
/// </summary>
/// <returns>true if iteration can proceed to the next item, false otherwise</returns>
publicboolMoveNext()
{
_currentItemIndex=this._leftIndex+(this._rightIndex-this._leftIndex)/2;
if(_comparer.Compare(_item,Current)<0)
{
_rightIndex=_currentItemIndex-1;
}
elseif(_comparer.Compare(_item,Current)>0)
{
_leftIndex=_currentItemIndex+1;
}
else
{
returnfalse;
}
returntrue;
}
publicvoidReset()
{
this._currentItemIndex=-1;
_leftIndex=0;
_rightIndex=_collection.Count-1;
}
publicvoidDispose()
{
//not implementing this, since there are no managed resources to release
}
}
}