SearchUtil类:
using System;
namespace searchdemo.Utils
{
public class SearchUtil<T> where T : struct, IComparable<T>
{
public static int binarySearch(T[] table, T value, int low, int high)
{
while (low <= high)
{
int mid = (low + high) / 2;
if (table[mid].Equals(value))
{
return mid;
}
else if (table[mid].CompareTo(value) < 0)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
public static int binarySearch(T[] table, T value)
{
int n = table.Length;
return SearchUtil<T>.binarySearchRec(table, value, 0, n - 1);
}
public static int binarySearchRec(T[] table, T value, int low, int high)
{
if (low > high)
{
return -1;
}
int mid = (low + high) / 2;
if (table[mid].Equals(value))
{
return mid;
}
if (table[mid].CompareTo(value) < 0)
{
return SearchUtil<T>.binarySearchRec(table, value, mid + 1, high);
}
else
{
return SearchUtil<T>.binarySearchRec(table, value, low, mid - 1);
}
}
}
}
主程序类:
using System;
using searchdemo.Utils;
namespace searchdemo
{
class Program
{
static void Main(string[] args)
{
int[] table = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int index = SearchUtil<int>.binarySearch(table, 1);
Console.WriteLine($"1在数组中的第{index}个位置");
}
}
}
程序输出如下: