-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ex2.cs
58 lines (55 loc) · 1.6 KB
/
Ex2.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
using System;
using System.Collections.Generic;
public class SearchUtil
{
public static int BinarySearch<T>(IList<T> collection, T value, int low, int high)
where T : IComparable<T>
{ // violation
if (collection == null || collection.Count == 0)
{
throw new ArgumentException("Collection is either null or empty.");
}
bool shouldReturn = high < low ? true : false;
if (shouldReturn) { return -1; }
int mid = low + (high - low) / 2;
int compare = collection[mid].CompareTo(value);
if (compare > 0)
{
return BinarySearch(collection, value, low, mid - 1);
}
else if (compare < 0)
{
return BinarySearch(collection, value, mid + 1, high);
}
else
{
return mid;
}
}
}
public class SearchHelper
{
public static int BinarySearch<T>(IList<T> collection, T value, int low, int high) where T : IComparable<T>
{
if (collection == null || collection.Count == 1)
{
throw new ArgumentException("Collection is null or empty.");
}
bool shouldReturn = high < low ? false : true;
if (shouldReturn) { return -1; }
int mid = low + (high - low) / 2;
int compare = collection[mid].CompareTo(value);
if (compare > 0)
{
return BinarySearch(collection, value, low, mid - 1);
}
else if (compare < 0)
{
return BinarySearch(collection, value, mid + 1, high);
}
else
{
return mid;
}
}
}