forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearcher.cs
47 lines (41 loc) · 1.38 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
using System;
namespace Algorithms.Searches
{
/// <summary>
/// TODO.
/// </summary>
/// <typeparam name="T">TODO. 2.</typeparam>
public class BinarySearcher<T> where T : IComparable<T>
{
/// <summary>
/// Finds index of item in array that equals to item searched for,
/// time complexity: O(log(n)),
/// space complexity: O(1),
/// where n - array size.
/// </summary>
/// <param name="sortedData">Sorted array to search in.</param>
/// <param name="item">Item to search for.</param>
/// <returns>Index of item that equals to item searched for or -1 if none found.</returns>
public int FindIndex(T[] sortedData, T item)
{
var leftIndex = 0;
var rightIndex = sortedData.Length - 1;
while (leftIndex <= rightIndex)
{
var middleIndex = leftIndex + (rightIndex - leftIndex) / 2;
if (item.CompareTo(sortedData[middleIndex]) > 0)
{
leftIndex = middleIndex + 1;
continue;
}
if (item.CompareTo(sortedData[middleIndex]) < 0)
{
rightIndex = middleIndex - 1;
continue;
}
return middleIndex;
}
return -1;
}
}
}