forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearcher.cs
47 lines (40 loc) · 1.39 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.Search;
/// <summary>
/// Binary Searcher checks an array for element specified by checking
/// if element is greater or less than the half being checked.
/// time complexity: O(log(n)),
/// space complexity: O(1).
/// Note: Array must be sorted beforehand.
/// </summary>
/// <typeparam name="T">Type of element stored inside array. 2.</typeparam>
public class BinarySearcher<T> where T : IComparable<T>
{
/// <summary>
/// Finds index of an array by using binary search.
/// </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;
}
}