-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathBinarySearch.cs
35 lines (31 loc) · 926 Bytes
/
BinarySearch.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
using System;
using System.Collections.Generic;
namespace PracticeQuestionsSharp.Algorithms
{
public static class BinarySearch
{
//Generic implementation of a binary search algorithm.
public static int Search<T>(this IList<T> collection, T data) where T : IComparable
{
int max = collection.Count - 1;
int min = 0;
while (min <= max)
{
int mid = min + (max - min) / 2;
int comparison = data.CompareTo(collection[mid]);
switch (comparison)
{
case 1:
min = mid + 1;
break;
case -1:
max = mid - 1;
break;
case 0:
return mid;
}
}
return -1;
}
}
}