-
Notifications
You must be signed in to change notification settings - Fork 1
/
BinaryRecursive.cs
36 lines (31 loc) · 976 Bytes
/
BinaryRecursive.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
using System;
namespace AlgorithmsAndDataStructures.Algorithms.Search
{
public class BinaryRecursive<T> : ISearchAlgorithm<T> where T : IComparable<T>
{
public int Search(T[] target, T value)
{
return target is null ? default : SearchInternal(target, 0, target.Length, value);
}
private static int SearchInternal(T[] target, int start, int end, T value)
{
if (start >= end)
{
return -1;
}
var mid = start + (end - start) / 2;
if (value.CompareTo(target[mid]) == 0)
{
return mid;
}
if (value.CompareTo(target[mid]) < 0)
{
return SearchInternal(target, start, mid, value);
}
else
{
return SearchInternal(target, mid + 1, end, value);
}
}
}
}