forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearcher.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
using System;
using System.Collections;
using System.Collections.Generic;
using Algorithms.Sorting;
namespace Algorithms.Search
{
public class BinarySearcher<T> : IEnumerator<T>
{
private readonly IList<T> _collection;
private readonly Comparer<T> _comparer;
private T _item;
private int _currentItemIndex;
private int _leftIndex;
private int _rightIndex;
/// <summary>
/// The value of the current item
/// </summary>
public T Current
{
get
{
return _collection[_currentItemIndex];
}
}
object IEnumerator.Current => Current;
/// <summary>
/// Class constructor
/// </summary>
/// <param name="collection">A list</param>
/// <param name="comparer">A comparer</param>
public BinarySearcher(IList<T> collection, Comparer<T> comparer)
{
if (collection == null)
{
throw new NullReferenceException("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>
public int BinarySearch(T item)
{
bool notFound = true;
if (item == null)
{
throw new NullReferenceException("Item to search for is not set");
}
Reset();
_item = item;
while ((_leftIndex <= _rightIndex) && notFound)
{
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>
public bool MoveNext()
{
_currentItemIndex = this._leftIndex + (this._rightIndex - this._leftIndex) / 2;
if (_comparer.Compare(_item, Current) < 0)
{
_rightIndex = _currentItemIndex - 1;
}
else if (_comparer.Compare(_item, Current) > 0)
{
_leftIndex = _currentItemIndex + 1;
}
else
{
return false;
}
return true;
}
public void Reset()
{
this._currentItemIndex = -1;
_leftIndex = 0;
_rightIndex = _collection.Count - 1;
}
public void Dispose()
{
//not implementing this, since there are no managed resources to release
}
}
}