using System;
namespace 算法
{
class Program
{
static void Main(string[] args)
{
// 已排序数组
var a = new[] { 1, 2, 4, 5, 7, 9, 23, 45, 67, 89 };
Console.WriteLine(BinarySearch(a,89));
Console.ReadLine();
}
/// <summary>
/// 二分查找
/// </summary>
/// <param name="x">数组</param>
/// <param name="find">要查找的值</param>
/// <returns></returns>
private static int BinarySearch(int[] x, int find)
{
int low = 0, high = x.Length - 1;
while (low <= high)
{
int mid = (low + high) / 2, cmp = x[mid].CompareTo(find);
if (cmp < 0)
{
low = mid + 1;
}
else if (cmp > 0)
{
high = mid - 1;
}
else
{
return mid;
}
}
return -(low + 1);
}
}
}